Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to merge an external dataframe with list components in R?

I am trying to merge the dataframe additions into each component of my list exlist where appropriate. Combined, the list should look like finlist.

exlist <- list(structure(list(name = c("A", "A", "A"), count = c(1, 5, 
7)), class = "data.frame", row.names = c(NA, -3L)), structure(list(
    name = c("B", "B", "B"), count = c(2, 2, 4)), class = "data.frame", row.names = c(NA, 
-3L)), structure(list(name = c("C", "C", "C"), count = c(5, 1, 
3)), class = "data.frame", row.names = c(NA, -3L)))
additions <- structure(list(name = c("A", "B", "C"), add = c(4, 6, 5)), class = "data.frame", row.names = c(NA, 
-3L))
finlist <- list(structure(list(name = c("A", "A", "A"), count = c(1, 5, 
7), add = c(4,4,4)), class = "data.frame", row.names = c(NA, -3L)), structure(list(
    name = c("B", "B", "B"), count = c(2, 2, 4), add = c(6,6,6)), class = "data.frame", row.names = c(NA, 
-3L)), structure(list(name = c("C", "C", "C"), count = c(5, 1, 
3), add = c(5,5,5)), class = "data.frame", row.names = c(NA, -3L)))

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can lapply a merge or dplyr::left_join:

lapply(exlist, left_join, additions, by = "name")
# [[1]]
#   name count add
# 1    A     1   4
# 2    A     5   4
# 3    A     7   4
# 
# [[2]]
#   name count add
# 1    B     2   6
# 2    B     2   6
# 3    B     4   6
# 
# [[3]]
#   name count add
# 1    C     5   5
# 2    C     1   5
# 3    C     3   5

(All in base R: lapply(exlist, merge, y = additions, by = "name", all.x = TRUE) for the same result.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading