Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In R, how to combine component-wise two lists which components have the same names?

Tags:

list

r

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!

like image 479
tflutre Avatar asked Feb 23 '23 17:02

tflutre


1 Answers

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)
like image 102
Joshua Ulrich Avatar answered Feb 26 '23 07:02

Joshua Ulrich