R: adding two data frames (different number of rows)

I have one data frame (df1):

Type     CA     AR     Total
alpha    2      3        5
beta     1      5        6
gamma    6      2        8
delta    8      1        9

I have another data frame (df2)

Type     CA     AR     Total
alpha    3      4        7
beta     2      6        8
delta    4      1        5

How can I add the two above 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 the code on this line:

new_df = df1 + df2

I get the following error:

‘+’ only defined for equally-sized data frames

How to add two data frames, perhaps by matching names in the "type" column?

Thanks in advance!

+4
source share
2 answers

(Slightly unmanaged rows due to aggregate()ordering behavior of output by column grouping, 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
+1
source

Library (dplyr)

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

All Articles