[英]R: Adding two dataframes (different number of rows)
I have one dataframe (df1): 我有一个数据帧(df1):
Type CA AR Total
alpha 2 3 5
beta 1 5 6
gamma 6 2 8
delta 8 1 9
I have another dataframe (df2) 我有另一个数据帧(df2)
Type CA AR Total
alpha 3 4 7
beta 2 6 8
delta 4 1 5
How can I add the above two data frames to get the following output: 如何添加以上两个数据帧以获得以下输出:
Type CA AR Total
alpha 5 7 12
beta 3 11 14
gamma 6 2 8
delta 12 2 14
If I use a code along this line: 如果我沿着这一行使用代码:
new_df = df1 + df2
I get the following error: 我收到以下错误:
‘+’ only defined for equally-sized data frames
How do I add the two dataframes, perhaps by matching the names under the "type" column? 如何添加这两个数据帧,可能是通过匹配“类型”列下的名称?
Thanks in advance!! 提前致谢!!
(Slightly out-of-order rows due to aggregate()
's behavior of ordering the output by the grouping column, but correct data.) (由于aggregate()
按分组列排序输出的行为,但由于数据正确,因此略有无序行。)
df1 <- data.frame(Type=c('alpha','beta', 'gamma','delta'), CA=c(2,1,6,8), AR=c(3,5,2,1), Total=c(5,6,8,9) );
df2 <- data.frame(Type=c('alpha','beta','delta'), AR=c(3,2,4), CA=c(4,6,1), Total=c(7,8,5) );
aggregate(.~Type,rbind(df1,setNames(df2,names(df1))),sum);
## Type CA AR Total
## 1 alpha 5 7 12
## 2 beta 3 11 14
## 3 delta 12 2 14
## 4 gamma 6 2 8
库(dplyr)
rbind(df1,df2)%>%group_by(Type)%>%summarise_each(funs(sum))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.