jeudi 13 mai 2021

How to apply ifelse function across multiple columns and create new columns in R

I would like to apply an ifelse function across multiple columns of my dataset and create new "rescored" columns. Here is a sample dataset:

data = data.frame(year = "2021",
                  month = sample(x = c(1:12), size = 10, replace = TRUE),
                  C1 = sample(x = c('Off', 'Yes'), size = 10, replace = TRUE),
                  C2 = sample(x = c('Off', 'Yes'), size = 10, replace = TRUE),
                  C3 = sample(x = c('Off', 'Yes'), size = 10, replace = TRUE),
                  C4 = sample(x = c('Off', 'Yes'), size = 10, replace = TRUE),
                  C5 = sample(x = c('Off', 'Yes'), size = 10, replace = TRUE),
                  C6 = sample(x = c('Off', 'Yes'), size = 10, replace = TRUE),
                  C7 = sample(x = c('Off', 'Yes'), size = 10, replace = TRUE),
                  C8 = sample(x = c('Off', 'Yes'), size = 10, replace = TRUE),
                  C9 = sample(x = c('Off', 'Yes'), size = 10, replace = TRUE),
                  C10 = sample(x = c('Off', 'Yes'), size = 10, replace = TRUE))

I would like to apply a function like this across all rows that begin with C:

rescored = data %>%
  mutate(T1 = ifelse(C1 == "Off", 1,
                     ifelse(C1 == "Yes", 0, NA)))

My real dataset has 50 or more rows that need this function applied. Is there a simple way to do this? I've tried using variations on "across" in dplyr like below but haven't been successful. I'm sure there is also an "apply" option.

rescored = data %>%
  mutate(across(C1:C50, ifelse(~ .x == "Off", 1,
                               ifelse(~.x == "Yes", 0, NA))))

Aucun commentaire:

Enregistrer un commentaire