将列向量应用于R中数组中每个矩阵的每一行

时间:2015-07-30 19:10:29

标签: arrays r matrix

如果我有阵列

> (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函数吗?

2 个答案:

答案 0 :(得分:1)

感谢大家的帮助!我相信正确的方法是

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)。

答案 1 :(得分:0)

<强> EDITED

这应该给你答案:

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

这有帮助吗?