Dear R masters,
I am trying to recode all questions containing values 1-10 (in this case just Q1) into Top2 box (1-8 should be 0 and 9-10 should be 100) and Yes/No questions so containing values 1 or 2 (in this case just Q2) into %Yes (1=100, 2=0). The original file contains multiple various variables co I am trying to pick up only these I need.
This is what I have done:
source <- data.frame(
stringsAsFactors = FALSE,
URN = c("aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg"),
Name = c("xxx", "xxx", "yyy", "yyy", "yyy", "zzz", "abc"),
Q1 = c(10, 5, 9, 7, 2, 4, 3),
Q2 = c(1, 2, 1, 1, 2, 1, 2),
Q3 = c(1, 4, 3, 2, 1, 2, 4),
Q4 = c(2019, 2020, 2020, 2019, 2020, 2021, 2021)
)
source
result <- source %>%
mutate_if(~is.numeric(.) && any(. == 2, na.rm = TRUE),
list(`Yes`= ~ case_when( . == 2 ~ 0,
. == 1 ~ 100))) %>%
mutate_if(~is.numeric(.) && any(. > 5, na.rm = TRUE),
list(`Top2`= ~ case_when( . >= 1 & . <= 8 ~ 0,
. >= 9 & . <= 10 ~ 100)))
result
but for some reason all numeric variables are recoded.
As a result I need two extra variables: Q2_Yes and Q1Top2.
How can I do it?
Can you help?