Recoding specific numerical variables into 0 or 100

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?

I think the issue is with the line above but I cannot fix it...

also, the second mutate takes into account variables created in the first one...

bit fuzzy on your needs but...


(resultx <- source %>%
  mutate(
    across(
      where(~ is.numeric(.) & all(. <= 2, na.rm = TRUE)),
      list(Yes = ~ case_when(
        . == 2 ~ 0,
        . == 1 ~ 100
      ))
    ),
    across(
      .cols = !ends_with("_Yes") & where(~ is.numeric(.) & any(. > 5 & .<2000, na.rm = TRUE)),
      list(Top2 = ~ case_when(
        . >= 1 & . <= 8 ~ 0,
        . >= 9 & . <= 10 ~ 100
      ))
    )
  ))

Of course!
Thank you!!!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.