With the base::replace function I want to change some values of column z based on the values of column y
library(tidyverse)
(df <- tibble(y = 10:13, z = 20:23))
#> # A tibble: 4 x 2
#> y z
#> <int> <int>
#> 1 10 20
#> 2 11 21
#> 3 12 22
#> 4 13 23
I have the data.frame val where column a the value to be used as condition and column b will be the replacement value.
(val <- tibble(a = c(10, 12), b = c(100, 200)))
#> # A tibble: 2 x 2
#> a b
#> <dbl> <dbl>
#> 1 10 100
#> 2 12 200
Using the following approach it is possible to get the desired result, but it only works if all the values inside val are inside df
df %>% mutate(z = replace(z, y %in% val$a, val$b))
#> # A tibble: 4 x 2
#> y z
#> <int> <dbl>
#> 1 10 100
#> 2 11 21
#> 3 12 200
#> 4 13 23
For example, if I update val to have values that are not in df, then:
(val <- tibble(a = c(1, 10, 12), b = c(1, 100, 200)))
#> # A tibble: 3 x 2
#> a b
#> <dbl> <dbl>
#> 1 1 1
#> 2 10 100
#> 3 12 200
and I run the code again ...
df %>% mutate(z = replace(z, y %in% val$a, val$b))
#> Warning in x[list] <- values: number of items to replace is not a multiple of
#> replacement length
#> # A tibble: 4 x 2
#> y z
#> <int> <dbl>
#> 1 10 1
#> 2 11 21
#> 3 12 100
#> 4 13 23
There are errors ... How can I fix this?
Created on 2021-02-19 by the reprex package (v1.0.0)