Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
347 views
in Technique[技术] by (71.8m points)

r - Adding all elements of two lists

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...