R 如何将两个数据帧相加和组合?
我有两个数据帧: 数据1:R 如何将两个数据帧相加和组合?,r,R,我有两个数据帧: 数据1: 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 数据2: ID com_alc_dd com_liv_dd
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
数据2:
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
我想合并两个数据帧,以获得两个数据帧的总和:
总和(数据1、数据2)
:
举个例子(假设data.frames是相同大小的矩阵)
d1试试这个例子(假设data.frames是相同大小的矩阵)
d1您也可以使用aggregate
names(df1) <- names(df2)
df3 <- rbind(df1, df2)
res <- aggregate(df3[,-1], by=list(df3$ID), sum)
names(df1)您还可以使用aggregate
names(df1) <- names(df2)
df3 <- rbind(df1, df2)
res <- aggregate(df3[,-1], by=list(df3$ID), sum)
names(df1)为什么不尝试合并ID
上的数据帧,然后求和。@rrs,因为我有很多variable@rrs我不明白你怎么能在这里使用merge
?@agstudy它不是一行程序,也不像你的解决方案那么好。但是您可以在ID
上merge
,然后为所需的每个总和创建新列。不漂亮,这就是我没有提交解决方案的原因。你为什么不尝试合并ID
上的数据帧,然后求和。@rrs,因为我有很多variable@rrs我不明白你怎么能在这里使用merge
?@agstudy它不是一行程序,也不像你的解决方案那么好。但是您可以在ID
上merge
,然后为所需的每个总和创建新列。不漂亮,这就是我没有提交解决方案的原因。
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
names(df1) <- names(df2)
df3 <- rbind(df1, df2)
res <- aggregate(df3[,-1], by=list(df3$ID), sum)