Reputation: 1040
I have data such as this:
data_in <- read_table2("condition Q11_1 Q11_2 Q11_3 Q11_4 Q11_5 Q11_6 Q11_7 Q11_8 Q11_9 Q11_10 Q11_11 Q11_12 Q11_13
1 2 5 5 2 5 5 5 5 2 5 5 2 2
0 1 1 1 2 2 5 5 5 1 2 2 2 1
1 6 5 6 6 6 6 5 6 5 6 6 6 6
0 6 6 6 6 6 6 6 6 6 6 6 6 6
1 5 6 6 6 6 6 6 6 6 6 6 6 5
1 6 6 6 6 6 6 6 6 5 5 6 6 5
")
I have a series of variables (from a survey) with the values (1,2,5,6). I want to change the values of a specific set of variables from 5 to 3 and the 6 to 4. In this example I've only included the variables Q11_1:Q11_13 that I am interested in changing. There about 100 other variables I have not included in the example. I also want this to apply when condition==1.
I know I can do this to to change all the columns that contain Q11:
survey %>%
mutate(across(contains("Q11"),.fns = ~ case_when(.x == 5 ~ 3,
.x == 6 ~ 4,
TRUE ~ .x)))
Now, I want to re-value all the columns that contain Q11 AND have the condition==1. I don't want those columns to be changed if the condition of that row==0.
Upvotes: 1
Views: 38
Reputation: 887108
We can use the &
within case_when
library(dplyr)
data_in %>%
mutate(across(starts_with('Q11'), ~
case_when(. == 5 & condition == 1 ~ 3,
. == 6 & condition == 6 ~ 4, TRUE ~ .)))
# A tibble: 6 x 14
# condition Q11_1 Q11_2 Q11_3 Q11_4 Q11_5 Q11_6 Q11_7 Q11_8 Q11_9 Q11_10 Q11_11 Q11_12 Q11_13
# <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#1 1 2 3 3 2 3 3 3 3 2 3 3 2 2
#2 0 1 1 1 2 2 5 5 5 1 2 2 2 1
#3 1 6 3 6 6 6 6 3 6 3 6 6 6 6
#4 0 6 6 6 6 6 6 6 6 6 6 6 6 6
#5 1 3 6 6 6 6 6 6 6 6 6 6 6 3
#6 1 6 6 6 6 6 6 6 6 3 3 6 6 3
Upvotes: 1