I need you help with this:
I have a list:
list(c(0,1), c(1,1), c(3,2))
how can i get the sum:
(0-1)+(1-1)+(3-2)
Not a big fan of Reduce
, do.call
is usually faster. In this case the unlist
solution seems to have a slight edge:
EDIT: @ds440 for the win!
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
Where ds
is the approach by @ds440 wrapped in a function.
This probably isn't the fastest way to calculate it, and it certainly uses more resources, but here's a completely different take on it:
> mylist = list(c(0,1), c(1,1), c(3,2))
> a = matrix(unlist(mylist), ncol=2, byrow=T)
> sum(a[,1]-a[,2])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With