Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R sum element X in list of vector

Tags:

list

r

vector

sum

I just started doing some R script and I can't figure out this problem.

I got a list of vector let say

myListOfVector <- list(
     c(1,2), 
     c(1,2), 
     c(1,2), 
     c(1,2)
)

what I want is the sum of each X element of each vector that are in my list base on the position of the element so that if I have 3 vector that contains (a, b, c), I will get the sum of each a, each b and each c in a list or vector

I know that each vector are the same length

What I seek is something like that

result <- sum(myListOfVector)
# result must be c(4, 8)

Does anybody have an idea ?

The only way I've been able to do it is by using a loop but it take so much time that I can't resign to do it.

I tried some apply and lapply but they don't seem to work like I want it to because all I have is one vector at a time.

Precision : The list of vector is returned by a function that I can't modify I need an efficient solution if possible

like image 325
Incognito Avatar asked Nov 24 '15 17:11

Incognito


1 Answers

A list of vectors of the same length can be summed with Reduce:

Reduce(`+`, myListOfVector)

Putting it in a matrix and using colSums or rowSums, as mentioned by @AnandaMahto and @JanLuba, might be faster in some cases; I'm not sure.


Side note. The example in the OP is not a list; instead, it should be constructed like

myListOfVector <- list( # ... changing c to list on this line
     c(1,2), 
     c(1,2), 
     c(1,2), 
     c(1,2)
)
like image 182
Frank Avatar answered Oct 18 '22 08:10

Frank