6

我需要你帮忙:

我有一个清单:

list(c(0,1), c(1,1), c(3,2))

我怎样才能得到总和:

(0-1)+(1-1)+(3-2)
4

4 回答 4

7

不是 的忠实粉丝Reducedo.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 的方法在哪里包装在一个函数中。

于 2013-02-28T20:20:14.727 回答
6

这可能不是计算它的最快方法,而且它肯定会使用更多资源,但这里有一个完全不同的看法:

> 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-02-28T22:25:24.703 回答
5

试试这个

# 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
于 2013-02-28T19:55:22.923 回答
3

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,所以我们需要使用-diff1st 减去 2nd。

sum(-sapply(mylist, FUN = diff))
于 2013-02-28T20:01:51.233 回答