在R中实现向量与函数输出逐元素相乘及批量列向运算
Got it, let's break this down step by step. First, let's make sure I understand your requirement correctly: you have a list of 10 vectors, and you want each vector in the list to element-wise multiply with the corresponding position/column in an array. Specifically, every element in the first vector gets multiplied by the first element (or entire first column) of the array, every element in the second vector by the second, and so on.
Let's start with sample data to make this concrete, then cover a few simple methods to implement this in R.
1. Scenario 1: Array is a 1D Vector of Scalars
If your "array" is just a 1D vector of 10 scalar values (one for each vector in your list), here's how to do it:
Step 1: Create Sample Data
# Make a list of 10 vectors (each vector has 5 elements here) vec_list <- lapply(1:10, function(x) rnorm(5)) # Create a 1D array (vector) of 10 scalars, one for each vector in the list scalar_arr <- 1:10 # Example values: 1, 2, ..., 10
Step 2: Perform Element-wise Multiplication
We can use Map() or mapply() to pair each vector in the list with the corresponding scalar and multiply:
# Using Map() - returns a list (matches the input list structure) result_list <- Map(function(vec, val) vec * val, vec_list, scalar_arr) # Alternatively, using mapply() - add SIMPLIFY=FALSE to keep it as a list result_list <- mapply(function(vec, val) vec * val, vec_list, scalar_arr, SIMPLIFY = FALSE)
2. Scenario 2: Array is a 2D Matrix (10 Columns)
If your array is a 2D matrix with 10 columns (and the number of rows matches the length of each vector in your list), we need to pair each vector with the corresponding column of the matrix:
Step 1: Create Sample Data
# Same list of 10 vectors (each with 5 elements) vec_list <- lapply(1:10, function(x) rnorm(5)) # Create a 5x10 matrix (5 rows, 10 columns) arr_matrix <- matrix(rnorm(5*10), nrow = 5, ncol = 10)
Step 2: Perform Element-wise Multiplication
First split the matrix into a list of columns, then use Map() or purrr::map2() (if you use the tidyverse):
# Base R approach: split matrix into columns, then multiply col_list <- split(arr_matrix, col(arr_matrix)) result_list <- Map(`*`, vec_list, col_list) # Tidyverse approach (using purrr) library(purrr) result_list <- map2(vec_list, col_list, `*`)
Key Notes
- Both methods preserve the original list structure: each element in
result_listis the product of the corresponding vector fromvec_listand the matching array element/column. - If your vectors have different lengths than the array columns, R will recycle values (which might not be what you want), so double-check that dimensions match first!
内容的提问来源于stack exchange,提问作者user7905871

