Home > Mobile >  Replace a value in a data frame from other dataframe in r
Replace a value in a data frame from other dataframe in r

Time:10-14

Hi I have two dataframes, based on the id match, i wanted to replace table a's values with that of table b.

sample dataset is here :

a = tibble(id = c(1, 2,3),
           type = c("a", "x", "y"))
b= tibble(id = c(1,3),
          type =c("d", "n"))

Im expecting an output like the following :

c= tibble(id = c(1,2,3),
          type = c("d", "x", "n"))

CodePudding user response:

In dplyr v1.0.0, the rows_update() function was introduced for this purpose:

rows_update(a, b)

# Matching, by = "id"
# # A tibble: 3 x 2
#      id type 
#   <dbl> <chr>
# 1     1 d    
# 2     2 x    
# 3     3 n    

CodePudding user response:

Here is an option using dplyr::left_join and dplyr::coalesce

library(dplyr)
a %>%
    rename(old = type) %>%
    left_join(b, by = "id") %>%
    mutate(type = coalesce(type, old)) %>%
    select(-old)
## A tibble: 3 × 2
#     id type 
#. <dbl> <chr>
#1     1 d    
#2     2 x    
#3     3 n    

The idea is to join a with b on column id; then replace missing values in type from b with values from a (column old is the old type column from a, avoiding duplicate column names).

  • Related