Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Sum together items in multiple lists of different length?

Tags:

r

I have the following lists:

l1 <- list(a = 3, b = 4, c = 8, d = 1)

l2 <- list(a = 3, b = 2, c = 5, d = 1, f = 4, g = 13)

How can merge both lists by summing the items in both lists based on their names, as:

l1 + l2 = list(a=6, b=6, c=13, d=2, f=4, g=13)
like image 981
Stan Avatar asked Mar 15 '23 19:03

Stan


1 Answers

You could approach it with dplyr as follows:

l1 <- list(a = 3, b = 4, c = 8, d = 1)
l2 <- list(a = 3, b = 2, c = 5, d = 1, f = 4, g = 13)

library(dplyr)

bind_rows(lapply(list(l1, l2), as.data.frame)) %>%
colSums(na.rm=TRUE) %>%
as.list()
like image 85
Benjamin Avatar answered Mar 17 '23 08:03

Benjamin