1

I want to add together all matrices in a list. Here is an example of what I'm trying to do:

## sets up the problem
m1 <- matrix(0,nrow=9,ncol=4)
row.pres <- lapply(1:4,function(x) seq(x,x+2))
m1.l <- lapply(1:4,function(y) {m1[row.pres[[y]],y] <- 1
                        return(m1)}
       )

I want to add up all the elements of m1.l to come up with a single matrix of the same dimension as each of them. Here is my solution:

test <- lapply(1:4,function(x) paste("m1.l[[",x,"]]",sep=''))
add.all <- paste(test,collapse="+")
eval(parse(text=add.all))

But there must be a better way! perhaps something via do.call?

AndrewMacDonald
  • 2,870
  • 1
  • 18
  • 31

1 Answers1

4
 > Reduce("+", m1.l)
      [,1] [,2] [,3] [,4]
 [1,]    1    0    0    0
 [2,]    1    1    0    0
 [3,]    1    1    1    0
 [4,]    0    1    1    1
 [5,]    0    0    1    1
 [6,]    0    0    0    1
 [7,]    0    0    0    0
 [8,]    0    0    0    0
 [9,]    0    0    0    0

This will add the first two together, then it will take the result and add the 3rd matrix to it. Then it will add that result to the fourth matrix, etc. until it's worked its way through the whole list.

GSee
  • 48,880
  • 13
  • 125
  • 145