Reputation: 529
zii=list()
zii[[1]]=c(1,2,3)
zii[[2]]=c(1,2,3)
zii[[3]]=c(1,2,3)
What is the best way to perform element-wise addition in the list , IE:
sum=c(1+1+1,2+2+2,3+3+3)=c(3,6,9)
I tried Reduce("+",zii)
and it is slow. Any other suggestions ?
Upvotes: 2
Views: 120
Reputation: 263382
I'm not sure whether this will be any faster. The data.frame
does a lot of validity checking:
> rowSums(data.frame(zii))
[1] 3 6 9
Could also try these if you get around to using microbenchmark. I'm guessing one of these will win and my money would be on the second one.:
> rowSums(do.call(cbind, zii))
[1] 3 6 9
> colSums(do.call(rbind, zii))
[1] 3 6 9
Looks like I lost my bet:
require(microbenchmark)
microbenchmark( Reduce("+",zii) ,
rowSums(data.frame(zii)),
rowSums(do.call(cbind, zii)),
colSums(do.call(rbind, zii)) )
#------------------------------------------------------
Unit: microseconds
expr min lq mean median uq
Reduce("+", zii) 26.975 28.1870 31.02119 30.0560 30.9695
rowSums(data.frame(zii)) 730.933 744.9015 776.36775 753.5785 787.2765
rowSums(do.call(cbind, zii)) 65.770 67.3800 71.94039 68.7050 70.1335
colSums(do.call(rbind, zii)) 61.202 62.8830 66.21362 64.1060 65.9130
max neval cld
57.958 100 a
1129.953 100 c
176.627 100 b
127.259 100 b
Upvotes: 4