Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R programming i need help finding sum of a list with 2 columns

Tags:

r

sum

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)
like image 615
George Kostakis Avatar asked Feb 28 '13 19:02

George Kostakis


2 Answers

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.

like image 180
adibender Avatar answered Nov 15 '22 07:11

adibender


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])
like image 45
ds440 Avatar answered Nov 15 '22 07:11

ds440