Overriding values in one data frame with the corrected values in another

Hi there!

I would like to make corrections to values in a data frame in a concise and reproducible way.

For example, here is the hypothetical (and much smaller) data frame with incorrect values I'm working with.

df <- tibble::tribble(
        ~id, ~var1, ~var2,
          1,    10,   "a",
          2,   200,   "b",
          3,    30,   "c",
          4,    40,   "d",
          5,  8989,   "e",
          6,    60,   "f"
        )

I receive Excel spreadsheets with ids, variables names, and corrected values:

corrections <- tibble::tribble(
                       ~id, ~var1,
                         2,    20,
                         5,    50
                       )

I would like to update my data frame with those corrected values:

df <- tibble::tribble(
        ~id, ~var1, ~var2,
          1,    10,   "a",
          2,    20,   "b",
          3,    30,   "c",
          4,    40,   "d",
          5,    50,   "e",
          6,    60,   "f"
        )

Any suggestions on how to do that?

Thank you very much!

André

I would do it as shown below.

library(tibble)

df <- tibble::tribble(
  ~id, ~var1, ~var2,
  1,    10,   "a",
  2,   200,   "b",
  3,    30,   "c",
  4,    40,   "d",
  5,  8989,   "e",
  6,    60,   "f"
)

corrections <- tibble::tribble(
  ~id, ~var1,
  2,    20,
  5,    50
)

df
#> # A tibble: 6 x 3
#>      id  var1 var2 
#>   <dbl> <dbl> <chr>
#> 1     1    10 a    
#> 2     2   200 b    
#> 3     3    30 c    
#> 4     4    40 d    
#> 5     5  8989 e    
#> 6     6    60 f

df[corrections$id, "var1"] <- corrections$var1

df
#> # A tibble: 6 x 3
#>      id  var1 var2 
#>   <dbl> <dbl> <chr>
#> 1     1    10 a    
#> 2     2    20 b    
#> 3     3    30 c    
#> 4     4    40 d    
#> 5     5    50 e    
#> 6     6    60 f

Created on 2019-09-07 by the reprex package (v0.2.1)

3 Likes

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