R: Adding two dataframes (different number of rows) -


i have 1 dataframe (df1):

type     ca     ar     total alpha    2      3        5 beta     1      5        6 gamma    6      2        8 delta    8      1        9 

i have dataframe (df2)

type     ca     ar     total alpha    3      4        7 beta     2      6        8 delta    4      1        5 

how can add above 2 data frames following output:

type     ca     ar     total alpha    5      7        12 beta     3      11       14 gamma    6      2        8 delta    12     2        14 

if use code along line:

new_df = df1 + df2 

i following error:

‘+’ defined equally-sized data frames 

how add 2 dataframes, perhaps matching names under "type" column?

thanks in advance!!

(slightly out-of-order rows due aggregate()'s behavior of ordering output grouping column, 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 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -