简体   繁体   中英

R sum element X in list of vector

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

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)
)

you should first convert your list to a matrix:

mymatrix=matrix(myListOfVector,ncol=2,byrow=T)

and then use colSums:

colSums(mymatrix)

Best, Jan

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM