我需要你的帮助:
我有一个清单:
list(c(0,1), c(1,1), c(3,2))如何获得总和:
(0-1)+(1-1)+(3-2)发布于 2013-03-01 06:25:25
这可能不是计算它的最快方法,而且它肯定会使用更多的资源,但这里有一个完全不同的观点:
> mylist = list(c(0,1), c(1,1), c(3,2))
> a = matrix(unlist(mylist), ncol=2, byrow=T)
> sum(a[,1]-a[,2])发布于 2013-03-01 04:20:15
do.call不是Reduce的狂热粉丝,它通常更快。在这种情况下,unlist解决方案似乎有一点优势:
编辑: @ds440为胜利!
expr min lq median uq max
1 do.call(sum, lapply(List, function(z) -diff(z))) 63.132 67.7520 70.061 72.7560 291.406
2 ds(List) 6.930 10.5875 11.935 12.7040 51.584
3 Reduce("+", lapply(List, function(x) -sum(diff(x)))) 78.530 81.6100 83.727 87.1915 855.355
4 sum(-sapply(List, diff)) 88.155 91.4260 94.121 97.2005 955.442
5 sum(-unlist(lapply(List, diff))) 57.358 60.4375 61.785 63.5170 145.126其中ds是@ds440封装在函数中的方法。
发布于 2013-03-01 03:55:23
尝尝这个
# Sum of the first differences of your list
> (Sumlist <- lapply(List, function(x) -sum(diff(x))))
[[1]]
[1] -1 # this is (0-1)
[[2]]
[1] 0 # this is (1-1)
[[3]]
[1] 1 # this is (3-2)
# Total sum of your list
> Reduce('+', Sumlist) # this is (0-1)+(1-1)+(3-2)
[1] 0https://stackoverflow.com/questions/15144436
复制相似问题