Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add two dataframes; same dimension; different order column

Tags:

r

I have a dataframe, df1:

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

and a dataframe, df2:

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

I want to add the two dataframes such that the values under "CA" are added together and that the values under "AR" are added together. Basically, the values under each heading should be added together.

The resulting df should look like this:

    Type     AR     CA     Total
    alpha    6      6        12
    beta     7      7        14
    gamma    11     7        18
    delta    5      9        14

For example: (AR, gamma) = 2 + 9 = 11

like image 522
user4918087 Avatar asked Sep 26 '26 20:09

user4918087


2 Answers

The safest way would probably be to bind and aggregate

aggregate(.~Type, rbind(df1,df2), sum)
#    Type CA AR Total
# 1 alpha  6  6    12
# 2  beta  7  7    14
# 3 delta  9  5    14
# 4 gamma  7 11    18

The rbind.data.frame function pays attention to column names so it will properly stack your values.

like image 183
MrFlick Avatar answered Sep 28 '26 11:09

MrFlick


I'll repeat my suggestion from the comments last time -- consider putting Type in rownames:

DF1 <- data.frame(df1[-1],row.names=df1$Type)
DF2 <- data.frame(df2[-1],row.names=df2$Type)

From here, adding is straightforward:

DF1 + DF2[names(DF1)]
#       CA AR Total
# alpha  6  6    12
# beta   7  7    14
# gamma  7 11    18
# delta  9  5    14

A couple of caveats: If your rows are not ordered the same way, this will not work correctly (that's why @MrFlick's approach is "safe"). Also, the extension to more data frames isn't so elegant here:

Reduce(`+`,lapply(list(DF2,DF3,DF4),`[`,order(names(DF1))),init=DF1) # here
aggregate(.~Type, rbind(df1,df2,df3,df4), sum)                       # @MrFlick
like image 30
Frank Avatar answered Sep 28 '26 11:09

Frank



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!