如何在R中的两个data.frames中创建(不平衡)面板?

时间:2014-03-07 07:41:50

标签: r merge dataframe panel

我有两个data.frames,我想合并并变成一个面板。第一个data.frame是平衡面板,第二个是不平衡面板:

第一个data.frame看起来像这样:

date1 <- c("2012-01-01","2012-01-02","2012-01-03","2012-01-04","2012-01-05","2012-01-01","2012-01-02","2012-01-03","2012-01-04","2012-01-05")
company1 <- c("A","A","A","A","A","B","B","B","B","B")
ret1 <- c(-0.01, -0.013, 0.02, 0.032, -0.002, 0.022, 0.012, 0.031, -0.018, -0.034)

mydf1 <- data.frame(date1, company1, ret1)
mydf1

        date1 company1   ret1
1  2012-01-01        A -0.010
2  2012-01-02        A -0.013
3  2012-01-03        A  0.020
4  2012-01-04        A  0.032
5  2012-01-05        A -0.002
6  2012-01-01        B  0.022
7  2012-01-02        B  0.012
8  2012-01-03        B  0.031
9  2012-01-04        B -0.018
10 2012-01-05        B -0.034

第二个data.frame看起来像这样:

date2 <- c("2012-01-02","2012-01-04","2012-01-05","2012-01-01","2012-01-04")
company2 <- c("A","A","A","B","B")
class2 <- c("p", "p", "x", "n", "x")

mydf2 <- data.frame(date2, company2, class2)
mydf2

       date2 company2 class2
1 2012-01-02        A      p
2 2012-01-04        A      p
3 2012-01-05        A      x
4 2012-01-01        B      n
5 2012-01-04        B      x

所以第一行和第二行实际上是一样的:日期和公司名称。现在我想将第一个数据帧的剩余列(此处为:ret1)放入第二个数据帧。当然,我希望他们在正确的行。我怎样才能做到这一点?小组应如下所示:

        date  company  class     ret
1 2012-01-02        A      p  -0.013
2 2012-01-04        A      p   0.032
3 2012-01-05        A      x  -0.002
4 2012-01-01        B      n   0.022
5 2012-01-04        B      x  -0.018

1 个答案:

答案 0 :(得分:2)

我认为你可以使用合并。但是可能首先更改列名以获得所需的输出。

names(mydf1)=c("date","company","ret")
names(mydf2)=c("date","company","class")
merge(mydf1, mydf2, by.x=intersect(names(mydf1), names(mydf2)))

另见: Matching multiple columns on different data frames and getting other column as result