hxd1011 - 1 year ago 76
R Question

# How can I effectively sum up matrices in a list (without loop) in R?

Suppose I have a function return 2 matrices. For each input i.

``````f<-function(i){
m1=matrix(i,ncol=5,nrow=5)
m2=matrix(i*10,ncol=5,nrow=5)
r=list(m1=m1,m2=m2)
return(r)
}
d=lapply(1:3,f)
``````

How can I get following 2 things without for loop?

``````d[[1]]\$m1+d[[2]]\$m1+d[[3]]\$m1
d[[1]]\$m2+d[[2]]\$m2+d[[3]]\$m2
``````

I tried
`sum(lapply(1:3,function(x) (d[[x]]\$m1)))`
for m1 but does not work.

You can use `Reduce`:

``````Reduce("+", lapply(d, function(x) x\$m1))
``````

You can also get both `m1` and `m2` using `transpose`, `map` and `reduce` from the purrr package:

``````library(purrr)
map(transpose(d), reduce, `+`)
``````

This returns:

``````\$m1
[,1] [,2] [,3] [,4] [,5]
[1,]    6    6    6    6    6
[2,]    6    6    6    6    6
[3,]    6    6    6    6    6
[4,]    6    6    6    6    6
[5,]    6    6    6    6    6

\$m2
[,1] [,2] [,3] [,4] [,5]
[1,]   60   60   60   60   60
[2,]   60   60   60   60   60
[3,]   60   60   60   60   60
[4,]   60   60   60   60   60
[5,]   60   60   60   60   60
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download