0

I have multiple data frames, for example: data frame 1

  V1 V2
1 Charlie 30
2 Tom 50
3 Anna 20

data frame 2

  V1 V2
1 Tom 30
2 Anna 10
3 Julia 60

how can I migrate these data frame into same one and add the second columns if the first column value was same:

  V1 V2
1 Charlie 30
2 Tom 80
3 Anna 30
4 Julia 60
Daniel Chen
  • 1,933
  • 5
  • 24
  • 33

1 Answers1

3

We can use tidyverse. We use bind_rows to bind the multiple datasets together, then grouped by 'V1', get the sum of 'V2'

library(tidyverse)
bind_rows(df1,df2) %>%
        group_by(V1) %>% 
        summarise(V2 = sum(V2))

Or using data.table, we can place the datasets in a list, use rbindlist to bind the datasets in the list, then grouped by 'V1', get the sum of 'V2'

library(data.table)
rbindlist(list(df1, df2))[, .(V2 = sum(V2)), by = V1]

Or with base R, by rbinding the datasets, use aggregate to get the sum of 'V2' grouped by 'V1'

aggregate(V2 ~V1, rbind(df1, df2), FUN = sum)
#       V1 V2
#1    Anna 30
#2 Charlie 30
#3   Julia 60
#4     Tom 80
akrun
  • 874,273
  • 37
  • 540
  • 662