zii=list()
zii[[1]]=c(1,2,3)
zii[[2]]=c(1,2,3)
zii[[3]]=c(1,2,3)
在列表中执行元素添加的最佳方法是什么,即:
sum=c(1+1+1,2+2+2,3+3+3)=c(3,6,9)
我尝试了 Reduce("+",zii)
但速度很慢。还有其他建议吗?
最佳答案
我不确定这是否会更快。 data.frame
进行了大量的有效性检查:
> rowSums(data.frame(zii))
[1] 3 6 9
如果您开始使用微基准测试,也可以尝试这些。我猜其中一个会赢,而我的钱会花在第二个上。:
> rowSums(do.call(cbind, zii))
[1] 3 6 9
> colSums(do.call(rbind, zii))
[1] 3 6 9
看来我输了:
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
关于r - 在 R 中向列表中添加元素的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36229749/