4

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

user4918087
  • 421
  • 1
  • 6
  • 14
  • `df1[df1$Type %in% df2$Type, ] + df2[df2$Type %in% df1$Type, ]` is halfway there. Then consider an rbind. – Hugh May 31 '15 at 00:04
  • 2
    Also your columns don't match -- is that a problem? – Hugh May 31 '15 at 00:05
  • Assuming you want to add CA values to CA values (which doesn't appear to be the case in your desired output but i'm not sure if that's a mistake or not), then the answer I gave to your [last question](http://stackoverflow.com/questions/30539527/r-add-two-dataframes-same-dimension-different-order-column) will work with unequal numbers of rows. – MrFlick May 31 '15 at 00:34

2 Answers2

1

(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
bgoldst
  • 34,190
  • 6
  • 38
  • 64
0

library(dplyr)

rbind(df1,df2)%>%group_by(Type)%>%summarise_each(funs(sum))
Shenglin Chen
  • 4,504
  • 11
  • 11