我希望你能帮我解决以下问题:
我有一个列表:
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])
byrow = TRUE
,或者你的 mylist
和 OP 的不同吗? - adibendermylist = list(c(0,1), c(1,1), c(3,2))
是的,你完全正确,抱歉! - ds440试试这个
# 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
diff(Reduce('+', List))
。 - Arunsapply
或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)
表示第二个减去第一个,因此我们需要使用-diff
来进行第一个减去第二个。sum(-sapply(mylist, FUN = diff))