In R, how to combine component-wise two lists which components have the same names?
here are my data:
l1 <- list(a=1, b=2)
l2 <- list(a=10, b=20)
I want to combine them in a component-wise manner. For instance, if I want to add the values of each component of l1 to the values of the same component in l2, I would do:
l <- list(a=l1$a+l2$a, b=l1$b+l2$b)
If now I have several components, I can do:
l <- list()
for(c in names(l1))
l[[c]] <- l1[[c]] + l2[[c]]
However, my lists can have lots of components, and I may need to do it with more than two lists (each always having the same component names as the others).
Since "for" loops are not recommended in R, is th开发者_运维问答ere any way of doing this using something like lapply, or merge, or by...?
Thanks!
It seems like you're looking for Map
:
identical(l, Map("+", l1, l2))
# [1] TRUE
Which is the same as:
mapply("+", l1, l2, SIMPLIFY=FALSE)
精彩评论