Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding all elements of two lists

Tags:

r

Suppose I have two lists, and corresponding elements of the lists are the same shape:

 e1=list(1,c(1,2,3),matrix(1:12,3,4))
 e2=list(1,c(1,2,3),matrix(1:12,3,4))

and I want to add these two lists element-by-element. Here's my solution which works for any length of lists and any shape of element, as long as they match and are addable:

> esum
function(e1,e2){
  e = list()
  for(i in 1:length(e1)){
    e[[i]]=e1[[i]]+e2[[i]]
  }
  e
}
> esum(e1,e2)

but it just seems ugly, and probably the kind of thing that can be done in a one-liner.

This is stage one of the problem, which is actually to add up a whole list of many of these lists, but once esum is defined its just Reduce:

 > ee = list(e1,e2,e1,e1,e2)
 > Reduce(esum,ee)[[3]]  # lets just check [[3]] for now
      [,1] [,2] [,3] [,4]
 [1,]    5   20   35   50
 [2,]   10   25   40   55
 [3,]   15   30   45   60

So, anyone got a one-liner for these?

Yes I know one-liners aren't always the best things.

like image 351
Spacedman Avatar asked Oct 26 '11 13:10

Spacedman


1 Answers

Something like

   mapply("+",e1,e2)

works for the first part ...

Reduce( function(x,y) mapply("+",x,y),ee)[[3]]

There may be something even slicker. Reduce doesn't take a ... argument so we can't get away with Reduce(mapply,ee,FUN="+")[[3]]

like image 101
Ben Bolker Avatar answered Sep 27 '22 17:09

Ben Bolker