Combining row entries in two files while adding weights where the names are common

StackOverflow https://stackoverflow.com/questions/22800580

  •  25-06-2023
  •  | 
  •  

Вопрос

I am facing a problem while trying to combining two data frames into one.

Data frame structure :1  
    FROM        TO          WEIGHT
1   abc_1   Dummy           100
2   abc_2   Dummy           20
3   xyz_1   abc_3           40

Data frame structure :1  
    FROM        TO          WEIGHT
1   abc_4   Dummy_7         100
2   abc_7   Dummy_9         2000
3   xyz_1   abc_3           400

I want to combine two data frames with the same structure and add the weights when the FROM and TO fields are the same in both entries. Otherwise I just want to combine the entries in one with the entries in the other. I want a new dataframe that gives me the output

    FROM        TO          WEIGHT
1   abc_1   Dummy           100
2   abc_2   Dummy           20
**3 xyz_1   abc_3           440**
4   abc_4   Dummy_7         100
5   abc_7   Dummy_9         2000

Thanks

Это было полезно?

Решение

Just use aggregate by category to sum the various entries. Try using with on the 'rbind' value to get them in the same object.

  with(  rbind( df1, df2), aggregate(WEIGHT, list(FROM=FROM, TO=TO) , sum) ) 
   FROM      TO    x
1 xyz_1   abc_3  440
2 abc_1   Dummy  100
3 abc_2   Dummy   20
4 abc_4 Dummy_7  100
5 abc_7 Dummy_9 2000

Другие советы

with dplyr?

require(dplyr)
df1<-read.table(header=T,text="
FROM        TO          WEIGHT
1   abc_1   Dummy           100
2   abc_2   Dummy           20
3   xyz_1   abc_3           40")

df2<-read.table(header=T,text="
FROM        TO          WEIGHT
1   abc_4   Dummy_7         100
2   abc_7   Dummy_9         2000
3   xyz_1   abc_3           400")

dfmerged<-
rbind(df1,df2) %.% group_by(FROM,TO) %.% summarise (WEIGHT=sum(WEIGHT))

> dfmerged
Source: local data frame [5 x 3]
Groups: FROM

FROM      TO WEIGHT
1 abc_1   Dummy    100
2 abc_2   Dummy     20
3 xyz_1   abc_3    440
4 abc_4 Dummy_7    100
5 abc_7 Dummy_9   2000
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top