Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sum each single element in a list with other individual elements in R?

Similar questions have been asked before about summing elements of a list. But my problem is a little different than the other questions.

I have a list of vectors. I am trying to sum the 1st element of the 1st vector with each single element from the other vectors in my list. Then I want to sum the 2nd element in my 1st vector with every other individual element from the other vectors in my list… and so on.

Hopefully my example will explain what Im trying to do. For example, if my list looks like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

l <- list(
  a = c(1,2,3),
  b = c(10,4), 
  c = c(8,5)
)

Writing out explicitly what im trying to do would look like:

1+10+8
1+10+5
1+4+8
1+4+5
2+10+8
2+10+5
2+4+8
2+4+5
3+10+8
3+10+5
3+4+8
3+4+5

In other words, take:

 l[[1]][1] + l[[2]][1] + l[[3]][1]
 l[[1]][1] + l[[2]][1] + l[[3]][2]
 l[[1]][1] + l[[2]][2] + l[[3]][1]
 l[[1]][1] + l[[2]][2] + l[[3]][2]
 l[[1]][2] + l[[2]][1] + l[[3]][1]... and so on for each element

Consequently, my final desired output would look like:

[1] 19 16 13 10 20 17 14 11 21 18 15 12

Any suggestions as to how I could do this?

EDIT: Additionally, to complicate matters more, I need to return the values in the order that I show when I wrote out all the sums explicitly. So the result has to match my desired output.

>Solution :

To match your specific order, we can do

c(Reduce(function (u, v) outer(u, v, "+"), rev(l)))
# [1] 19 16 13 10 20 17 14 11 21 18 15 12
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading