[英]Apply column vector to each row of each matrix in array in R
如果我有阵列
> (arr = array(c(1,1,2,2), c(2,2,2)))
, , 1
[,1] [,2]
[1,] 1 2
[2,] 1 2
, , 2
[,1] [,2]
[1,] 1 2
[2,] 1 2
那么如何将列向量c(3,3)应用于每个矩阵的每一行并将它们相加呢? 所以本质上,我需要做4 * c(1,2)%*%c(3,3)。 可以在此处使用apply函数吗?
谢谢大家的帮助! 我相信正确的方法是
sum(apply(arr, c(1,3), function(x) x %*% c(1,2,3)))
在这里,我们将向量[1,2,3]点缀到数组中称为arr的每个矩阵的每一行中,并将它们求和。 请注意,这里我将数组更改为
arr = array(c(1,2,3,4,5,6,7,8,9,10,11,12), c(2,3,2))
arr
, , 1
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
, , 2
[,1] [,2] [,3]
[1,] 7 9 11
[2,] 8 10 12
现在我们在其中行的向量是c(1,2,3)而不是原始帖子中的c(3,3)。
已编辑
这应该给你答案:
l <- list(matrix(c(1,1,2,2), ncol = 2),
matrix(c(1,1,2,2), ncol = 2))
l
#[[1]]
# [,1] [,2]
# [1,] 1 2
# [2,] 1 2
#
# [[2]]
# [,1] [,2]
# [1,] 1 2
# [2,] 1 2
ivector <- c(3, 3) # a vector that is multiplied with the rows of each listelement
# apply over all listelements
res <- lapply(l, function(x, ivector){
#apply to all rows of the matrizes
apply(x, 1, function(rowel, ivector){
return(sum(rowel %*% ivector))
}, ivector = ivector)
}, ivector = ivector)
res
#[[1]]
#[1] 9 9
#
#[[2]]
#[1] 9 9
# And finally sum up the results:
sum(Reduce("+", res))
#[1] 36
有帮助吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.