user4918087
user4918087

Reputation: 421

R: Adding two dataframes (different number of rows)

I have one dataframe (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)

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!!

Upvotes: 4

Views: 929

Answers (2)

bgoldst
bgoldst

Reputation: 35314

(Slightly out-of-order rows due to aggregate()'s behavior of ordering the output by the grouping column, but correct data.)

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

Upvotes: 1

Shenglin Chen
Shenglin Chen

Reputation: 4554

library(dplyr)

rbind(df1,df2)%>%group_by(Type)%>%summarise_each(funs(sum))

Upvotes: 0

Related Questions