1

this is very similar to

Is there an R function for the element-wise summation of the matrices stored as elements in single list object?

How can I do list summation element-wise in R?

For example, I want

temp1<-list(c(rep(0,6)),c(1,2,3,4,5,6))
temp2<-list(c(2,3,4,5,6,7))

to yield

 3,5,7,9,11,13     

Just simple temp1[[2]] + temp2 doesn't work. Is there a special formula for it?

Community
  • 1
  • 1
Hannah Lee
  • 75
  • 11
  • 2
    Please provide a reproducible example of what your lists look like. Also, does this have to generalize to situations where you have multiple lists or multiple items in each list? Or are you just adding two vectors from different lists? – Marius May 18 '17 at 04:46
  • I am trying to add different list : one is subset of list and the other is just list itself. what lists look like is posted in here temp1 is composed of list 2, and I want only temp1[[[2]]] and the other list is composed of numeric – Hannah Lee May 18 '17 at 04:49
  • Do both vectors in the list have same length? You can simply try with mapply like: `list(mapply(FUN = sum,temp2,temp1[[2]]))`. – tushaR May 18 '17 at 04:52
  • 1
    this looks like the `+` operator would suffice. Have you tried something like `mapply("+",a,b)` where the lists are `a` and `b`? – Aramis7d May 18 '17 at 04:54
  • 2
    `temp1[[2]] + temp2[[1]]` – Ronak Shah May 18 '17 at 04:54

3 Answers3

3

We can use Map

Map(`+`, temp1, temp2)[[2]]
akrun
  • 874,273
  • 37
  • 540
  • 662
1

Assuming that both the vectors in the list are of same length:

lst=list(a=c(1,2,3,4,5,6),b=c(2,3,4,5,6,7))   
list(mapply(FUN = sum,lst$a,lst$b))'.
tushaR
  • 3,083
  • 1
  • 20
  • 33
0

In my case, I have a list of more than 2 elements, where each element is a 2x2 matrix. I want to add up each of these 2x2 matrices, and I can do that by:

my_list <- c(temp1, temp2) #make one list of the separate sublists

Reduce("+", my_list) #add the sublists together, element-wise

If you do or don't want to include the first of your three sublists, you can use Reduce("+", my_list) or Reduce("+", my_list[-1]), respectively.

Steve Walsh
  • 127
  • 1
  • 7