Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

r - Add two dataframes; same dimension; different order column

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...