如何在R中逐个将列表和向量相乘?

时间:2018-09-07 05:50:46

标签: r

我想逐个元素地将具有相同长度的矩阵和向量列表相乘,而不使用 for 循环。这是我想做的一个例子。

set.seed(1111) # To make the result reproducible
a <- list(matrix(1:9, nrow = 3), matrix(rexp(n = 9, rate = 1), nrow = 3))
b <- c(0.5, 1.5)
c <- list()
for(i in 1:2){
  c[[i]]=a[[i]]*b[i]
}

a
[[1]]
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9

[[2]]
          [,1]       [,2]      [,3]
[1,] 0.9793649 0.08094869 0.2668127
[2,] 1.4831377 1.50722214 0.1104620
[3,] 0.4776337 6.75746241 0.1140135

c
[[1]]
     [,1] [,2] [,3]
[1,]  0.5  2.0  3.5
[2,]  1.0  2.5  4.0
[3,]  1.5  3.0  4.5

[[2]]
          [,1]      [,2]      [,3]
[1,] 1.4690473  0.121423 0.4002191
[2,] 2.2247065  2.260833 0.1656930
[3,] 0.7164505 10.136194 0.1710202

要执行此工作而不使用上面出现的 for 循环,我应该使用哪个功能?

2 个答案:

答案 0 :(得分:1)

如果将矩阵列表转换为3d数组,则可以轻松地进行此操作而不会产生任何循环。

library(abind)
a1 <- do.call(abind, c(a, list(along = 3)))
#, , 1
#
#     [,1] [,2] [,3]
#[1,]    1    4    7
#[2,]    2    5    8
#[3,]    3    6    9
#
#, , 2
#
#          [,1]       [,2]      [,3]
#[1,] 0.9793649 0.08094869 0.2668127
#[2,] 1.4831377 1.50722214 0.1104620
#[3,] 0.4776337 6.75746241 0.1140135

#permute first and third dimension before and after multiplication
aperm(aperm(a1, c(3, 2, 1)) * b, c(3, 2, 1))
# , , 1
# 
#      [,1] [,2] [,3]
# [1,]  0.5  2.0  3.5
# [2,]  1.0  2.5  4.0
# [3,]  1.5  3.0  4.5
# 
# , , 2
# 
#           [,1]      [,2]      [,3]
# [1,] 1.4690473  0.121423 0.4002191
# [2,] 2.2247065  2.260833 0.1656930
# [3,] 0.7164505 10.136194 0.1710202

答案 1 :(得分:1)

Map(`*`, a, b)

或等价物

mapply(`*`, a, b, SIMPLIFY = FALSE)