case_when()
1. Recode values using a wide formatted data dictionary
Review the data (d24)
# A tibble: 3 x 3
stu_id q1 q2
<dbl> <dbl> <dbl>
1 1 1 1
2 2 -99 1
3 3 -99 -99
Review our current wide formatted data dictionary (dict_wide)
# A tibble: 3 x 4
var_name type raw_value transformation
<chr> <chr> <chr> <chr>
1 stu_id numeric 1-10 NA
2 q1 numeric 1 = Selected, -99 = Not selected -99 -> 0
3 q2 numeric 1 = Selected, -99 = Not selected -99 -> 0
Select all variables with the same recoding logic (-99 -> 0)
recode_multi_select <- dict_wide %>%
dplyr::filter(transformation == "-99 -> 0") %>%
dplyr::pull(var_name)
recode_multi_select
[1] "q1" "q2"
Now we can use that vector of variable names to recode these variables ll at once.
d24 %>%
dplyr::mutate(dplyr::across(
dplyr::all_of(recode_multi_select),
~dplyr::case_when(
. == -99 ~ 0,
TRUE ~ .
)))
# A tibble: 3 x 3
stu_id q1 q2
<dbl> <dbl> <dbl>
1 1 1 1
2 2 0 1
3 3 0 0
Go to Recode using long formatted data dictionary
Return to Recode