Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
410 views
in Technique[技术] by (71.8m points)

r - How to sum and combine two data frames?

I have two data frames:

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

I want to combine the two data frames, so as to obtain the sum of the two:

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this for example( assuming that your data.frames are matrix of the same size)

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

EDIT general solution

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...