合并两个数据框 [英] Merging two data frames

查看:166
本文介绍了合并两个数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据框:

Date,Year,Austria,Germany,...
1969-12-31,1969,96.743,95.768,...
1970-01-30,1970,95.515,95.091,...
1970-02-27,1970,95.075,95.235,...

最终,我想将此数据框架与另一个看起来像这样的框架合并:

Ultimately, I would like to merge this data frame with another one that looks like this:

Year,Country,Exp,...
1969,Austria,1,...
1970,Austria,0,...
1969,Germany,0,...
1970,Germany,1,...

我看到的方式是,必须将第一个数据帧更改为以下格式:

The way I see it, I would have to change the first data frame to the following format:

Date,Year,Country,Exp,…
1969-12-31,1969,Austria,96.743,...
1970-01-30,1970,Austria,95.515,...
1970-02-27,1970,Austria,95.075,...
1969-12-31,1969,Germany,95.768,...
1970-01-30,1970,Germany,95.091,...
1970-02-27,1970,Germany,95.235,...

然后,我可以使用合并功能,并使用Year和Country(一对多)合并它们.

Then, I can just use the merge function and merge them (one-to-many) using Year and Country.

我尝试按照上面的建议转换数据帧.但是,我唯一想到的方法是使用几个复杂的"for"循环.如果有人有更简单的方法,将不胜感激.另外,如果您认为可以以更简单的方式合并这两个数据框,那也将非常有用.

I have tried to transform the data frame as suggest above. However, the only way I can think of is to use a couple of complicated "for" loops. It would be greatly appreciated if someone had an easier approach. Also, if you think that merging those two data frames can be done in an easier fashion that would be great too.

推荐答案

您需要融合的第一个数据帧.

The first data frame you need to melt.

library(reshape)
melt(dat, id.vars="Date,Year") # may need to add ...,c())

重命名新列以匹配您的其他data.frame.

Rename the new columns to match your other data.frame.

然后合并(或者您可能更喜欢使用plyr软件包加入)

Then merge (or you might prefer to join, using the plyr package)

merge(dat,dat2, by=c("Date","Country"))

或:

library(plyr)
join(dat,dat2, by=c("Date","Country"))

我更喜欢join函数,因为它比合并更直观,尤其是在有NA值的情况下.

I prefer the join function, because it acts much more intuitively than merge, especially in the case where there are NA values.

这篇关于合并两个数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆