合并大量数据。frame [duplicate]

时间:2021-06-08 22:55:02

Possible Duplicate:
Merge multiple data frames in a list simultaneously

可能的重复:在一个列表中同时合并多个数据帧

example data.frames:

示例data.frames:

 df1 = data.frame(id=c('1','73','2','10','43'),v1=c(1,2,3,4,5)) <br>
 df2 = data.frame(id=c('7','23','57','2','62','96'),v2=c(1,2,3,4,5,6)) <br>
 df3 = data.frame(id=c('23','62'),v3=c(1,2)) <br>

Note: id is unique for each data.frame. I want the resulting matrix to look like

注意:id对于每个数据都是唯一的。我希望得到的矩阵是这样的

1      1 NA NA 
2      3  4 NA 
7      NA 1 NA 
10     4 NA NA 
23     NA 2  1 
43     5 NA NA 
57     NA 3 NA 
62     NA 5  2 
73     2 NA NA 
96     NA 6 NA

In this case, I only show 3 datasets, I actually have at least 22 of them so at the end I want a matrix of nx(22+1) where n is the number of ids for all 22 datasets.

在这种情况下,我只显示了3个数据集,实际上我至少有22个,所以最后我想要一个n(22+1)的矩阵,其中n是所有22个数据集的id数。

Given 2 datasets, I need to get their ids in the first column and 2nd and 3rd columns are filled with the values, if there is no value exists, then input NA instead.

给定2个数据集,我需要在第一列中得到它们的id,第二和第三列中填充了这些值,如果没有值,则输入NA。

1 个解决方案

#1


116  

Put them into a list and use merge with Reduce

将它们放入列表并使用merge with Reduce

Reduce(function(x, y) merge(x, y, all=TRUE), list(df1, df2, df3))
#    id v1 v2 v3
# 1   1  1 NA NA
# 2  10  4 NA NA
# 3   2  3  4 NA
# 4  43  5 NA NA
# 5  73  2 NA NA
# 6  23 NA  2  1
# 7  57 NA  3 NA
# 8  62 NA  5  2
# 9   7 NA  1 NA
# 10 96 NA  6 NA

You can also use this more concise version:

你也可以用这个更简洁的版本:

Reduce(function(...) merge(..., all=TRUE), list(df1, df2, df3))

#1


116  

Put them into a list and use merge with Reduce

将它们放入列表并使用merge with Reduce

Reduce(function(x, y) merge(x, y, all=TRUE), list(df1, df2, df3))
#    id v1 v2 v3
# 1   1  1 NA NA
# 2  10  4 NA NA
# 3   2  3  4 NA
# 4  43  5 NA NA
# 5  73  2 NA NA
# 6  23 NA  2  1
# 7  57 NA  3 NA
# 8  62 NA  5  2
# 9   7 NA  1 NA
# 10 96 NA  6 NA

You can also use this more concise version:

你也可以用这个更简洁的版本:

Reduce(function(...) merge(..., all=TRUE), list(df1, df2, df3))