通过一列在两个列表之间合并 data.frames

Merge data.frames between two lists by one single column

这里是我的两个列表的例子 data.frames:

df1 = data.frame(a = c(1,2,3,4,5,6,7))
df2 = data.frame(a = c(111,112,113,114))

lst1 = list(df1, df2)

df3 = data.frame(a = c(1,2,3,4,5,6,7,8,9,10), b = c(10,11,12,13,14,15,16,17,18,19))
df4 = data.frame(a = c(111,112,113,114,115,116,117,118,119), b = c(22,23,24,25,26,27,28,29,30))

lst2 = list(df3, df4)

我需要按列 alst1lst2 合并,以便 df1df3df2df4.

这是我想要的输出:

> output_lst
[[1]]
   a  b
   1 10
   2 11
   3 12
   4 13
   5 14
   6 15
   7 16

[[2]]
    a  b
1 111 22
2 112 23
3 113 24
4 114 25

我尝试了很多 lapplyMap 但没有结果。 谢谢

试试这个:

sapply(seq_len(length(lst1)), 
       function(i) list(merge(lst1[[i]], lst2[[i]], by = "a", all.x=TRUE)))

# [[1]]
  # a  b
# 1 1 10
# 2 2 11
# 3 3 12
# 4 4 13
# 5 5 14
# 6 6 15
# 7 7 16

# [[2]]
    # a  b
# 1 111 22
# 2 112 23
# 3 113 24
# 4 114 25

只是:

Map(merge, lst1, lst2)
#or more explicitly
Map(merge, lst1, lst2, by="a")

Map 基本上是一个美化的循环:

merge(lst1[[1]], lst2[[1]], by="a")
#and
merge(lst1[[2]], lst2[[2]], by="a")