如何对两个数据帧进行求和和组合?

时间:2014-06-09 17:44:40

标签: r

我有两个数据框:

DATA1:

ID    com_alc_cd   com_liv_cd   com_hyee_cd
A         1            0             0
B         0            0             1
D         0            0             0
C         0            1             0

DATA2:

ID     com_alc_dd   com_liv_dd   com_hyee_dd
B          0            2             0
A          1            0             2
C          0            1             0
D          0            1             0

我想组合两个数据帧,以获得两者的总和:

SUM(DATA1, DATA2)

    ID     com_alc   com_liv   com_hyee
    A         2          0         2
    B         0          2         1
    C         0          2         0
    D         0          1         0

2 个答案:

答案 0 :(得分:4)

以此为例(假设您的data.frames是相同大小的矩阵)

d1 <- DATA1[order(DATA1$ID),]  
d2 <- DATA2[order(DATA2$ID),]
data.frame(ID=d1$ID,as.matrix(subset(d1,select=-ID)) + 
                    as.matrix(subset(d2,select=-ID)))


 ID com_alc_cd com_liv_cd com_hyee_cd
1  A          2          0           2
2  B          0          2           1
4  C          0          2           0
3  D          0          1           0

编辑一般解决方案

library(reshape2)
## put the data in the long format
res <- do.call(rbind,lapply(list(DATA1,DATA2),melt,id.vars='ID'))
## polish names
res$variable <- gsub('(.*_.*)_.*','\\1',res$variable)
## wide format and aggregate using sum
dcast(ID~variable,data=res,fun.aggregate=sum)

 ID com_alc com_hyee com_liv
1  A       2        2       0
2  B       0        1       2
3  C       0        0       2
4  D       0        0       1

答案 1 :(得分:4)

您也可以使用aggregate

names(df1) <- names(df2)
df3 <- rbind(df1, df2)
res <- aggregate(df3[,-1], by=list(df3$ID), sum)