所以我有这么大的数据框列表,其中一些具有匹配的列,而另一些则没有。我想重新绑定(bind)具有匹配列的列,并合并其他没有匹配列的列(基于变量年份、国家/地区)。但是,我不想手动检查所有数据帧以查看哪些数据帧具有匹配的列,哪些没有。
现在我想它看起来会是这样的:
myfiles = list.files(pattern="*.dta")
dflist <- lapply(myfiles, read.dta13)
for (i in 1:length(dflist)){
if colnames match
put them in list and rbindlist.
else put them in another list and merge.
}
除了不知道如何在 R 中准确执行此操作之外,我开始认为这毕竟行不通。
为了说明这一点,请考虑 6 个数据帧:
Dataframe 1: Dataframe 2:
Country Sector Emp Country Sector Emp
Belg A 35 NL B 31
Aus B 12 CH D 45
Eng E 18 RU D 12
Dataframe 3: Dataframe 4:
Country Flow PE Country Flow PE
NL 6 13 ... ... ...
HU 4 11 ... ...
LU 3 21 ...
Dataframe 5: dataframe 6:
Country Year Exp Country Year Imp
GER 02 44 BE 00 34
GER 03 34 BE 01 23
GER 04 21 BE 02 41
在这种情况下,我想要 rbind (dataframe 1,dataframe2) 和 rbind(dataframe 3, dataframe 4),并且我想根据变量国家/地区和年份合并数据帧 5 和 6。所以我的输出将是几个 rbinded/merged 数据帧..
最佳答案
如果列不相同,
Rbind
将失败。根据建议,您可以使用 dplyr
包中的 merge
或 left_join
。
也许这会起作用:do.call(left_join, dflist)
关于R 中的 R 绑定(bind)和合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38385883/