我需要你帮忙:
我有一个清单:
list(c(0,1), c(1,1), c(3,2))
我怎样才能得到总和:
(0-1)+(1-1)+(3-2)
不是 的忠实粉丝Reduce
,do.call
通常更快。在这种情况下,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 的方法在哪里包装在一个函数中。
这可能不是计算它的最快方法,而且它肯定会使用更多资源,但这里有一个完全不同的看法:
> mylist = list(c(0,1), c(1,1), c(3,2))
> a = matrix(unlist(mylist), ncol=2, byrow=T)
> sum(a[,1]-a[,2])
试试这个
# 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] 0
sapply
如果该模式(取第一个减去第二个元素的差异)是一致的,那么只需在对or的调用中编写一个匿名函数lapply
。
mylist <- list(c(0,1), c(1,1), c(3,2))
sapply(mylist, FUN = function(x) {x[1] - x[2]}) ## takes differences
sum(sapply(mylist, FUN = function(x) {x[1] - x[2]})) ## put it all together
这也可以通过该diff
功能实现(如@AnandaMahto 和@Jilber 使用的那样)。diff(0, 1)
给出 2nd 减去 1st,所以我们需要使用-diff
1st 减去 2nd。
sum(-sapply(mylist, FUN = diff))