library(dplyr, warn = FALSE)
set.seed(1)
values <- c("1+1", "1+2", "1+3", "1+4", "1+5", "1+6")
Df <- tibble(ab = sample(values, 10, replace = TRUE),
ba = sample(values, 10, replace = TRUE),
cd = sample(values, 10, replace = TRUE),
dc = sample(values, 10, replace = TRUE),
de = sample(values, 10, replace = TRUE),
ed = sample(values, 10, replace = TRUE))
Df
#> # A tibble: 10 x 6
#> ab ba cd dc de ed
#> <chr> <chr> <chr> <chr> <chr> <chr>
#> 1 1+2 1+2 1+6 1+3 1+5 1+3
#> 2 1+3 1+2 1+2 1+4 1+4 1+6
#> 3 1+4 1+5 1+4 1+3 1+5 1+3
#> 4 1+6 1+3 1+1 1+2 1+4 1+2
#> 5 1+2 1+5 1+2 1+5 1+4 1+1
#> 6 1+6 1+3 1+3 1+5 1+5 1+1
#> 7 1+6 1+5 1+1 1+5 1+1 1+2
#> 8 1+4 1+6 1+3 1+1 1+3 1+4
#> 9 1+4 1+3 1+6 1+5 1+5 1+4
#> 10 1+1 1+5 1+3 1+3 1+5 1+3
Created on 2018-10-29 by the reprex package (v0.2.1)
I need to change values in some data like this based on logical conditions. I could use a separate case_when
for each separate column, but the real dataset has alot of columns so I'd prefer not to...The output should be numeric, example for column ab
:
Df %>%
select(ab) %>%
mutate(ab = case_when(
ab == "1+1" | ab == "1+2" ~ 1,
ab == "1+3" | ab == "1+4" ~ 2,
ab == "1+5" | ab == "1+6" ~ 3
))
Created on 2018-10-29 by the reprex package (v0.2.1)
I guess this is a job for purrr (or some scoped dplyr verb??), but I can't really figure out where the case_when() would fit in this context, especially since the logicals are different because of different column names. Any help is greatly appreciated!