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

Time:08-09

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)))

CodePudding user response:

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.)

CodePudding user response:

You can use Map merge

> Map(merge, exlist, list(additions))
[[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

Or, probably you can try rbind merge split

> split(merge(do.call(rbind, exlist), additions, all = TRUE), ~name)
$A
  name count add
1    A     1   4
2    A     5   4
3    A     7   4

$B
  name count add
4    B     2   6
5    B     2   6
6    B     4   6

$C
  name count add
7    C     5   5
8    C     1   5
9    C     3   5
  • Related