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.
See Question&Answers more detail:
os