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 there 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With