Combining rows in data frames

Hello R Community,

I have two data frame that i want to combine in one data frame in the following manner.
If the row's ID are the same, then add their values.
If the row's ID doesn't match, then append the rows without change their values.

I was wondering if there is any function in R that makes this operation or if it is necessary create a new function.
This is an illustration of what I looking for.

Many thanks in advance


#Before combining  x & y
x
#>   ID value
#> 1  A     2
#> 2  B     3
#> 3  C     5

y
#>   ID value
#> 1  A     1
#> 2  B     4

# After combining x and y get a result like this, where similar row's ID the value are added and 
# if the row's ID are different, then the row is appended to the end. 

res
#>   ID value
#> 1  A     3
#> 2  B     7
#> 3  C     5

Created on 2021-07-24 by the reprex package (v2.0.0)

Using dplyr functions:

library(tidyverse)

x <- tibble(ID = c("A", "B", "C"), value = c(2, 3, 5))
y <- tibble(ID = c("A", "B"), value = c(1, 4))

bind_rows(x, y) %>% group_by(ID) %>% summarise(value = sum(value))
#> # A tibble: 3 × 2
#>   ID    value
#>   <chr> <dbl>
#> 1 A         3
#> 2 B         7
#> 3 C         5

Created on 2021-07-24 by the reprex package (v2.0.0)

1 Like

Many thanks @EconProf for the help.
That is wonderful! :smiley:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.