R sum element X in list of vector

25,855

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)
)
Share:
25,855
Incognito
Author by

Incognito

Updated on July 09, 2022

Comments

  • Incognito
    Incognito almost 2 years

    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

  • A5C1D2H2I1M1N2O1R2T1
    A5C1D2H2I1M1N2O1R2T1 over 8 years
    If it's already in a list, then there might not be any performance advantage. The colSums approach may even be slower because you'd have to convert the list to a matrix first.... +1