norm850
norm850

Reputation: 21

Apply column vector to each row of each matrix in array in R

If I have the array

> (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

then how could I apply a column vector, say c(3,3), to each row of each matrix and sum these up? So essentially, I need to do 4 * c(1,2) %*% c(3,3). Could an apply function be used here?

Upvotes: 0

Views: 109

Answers (2)

David
David

Reputation: 10232

EDITED

This should give you the answer:

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

Does that help?

Upvotes: 0

norm850
norm850

Reputation: 21

Thanks everyone for the help! I believe the correct method is

sum(apply(arr, c(1,3), function(x) x %*% c(1,2,3)))

which here we are dotting the vector [1,2,3] to each row of each matrix in our array called arr and summing them up. Note that here I changed the array to be

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

and now the vector we are dotting the rows with is c(1,2,3) instead of c(3,3) in the original post.

Upvotes: 1

Related Questions