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