2

I wrote this in R to dummy code a character variable that consists of either "0" or a character response (like "sh6sej"), so that all character responses go to 1 and all 0's go to 0. It works fine for the one variable.

However, is there a way to modify this so it dummy codes all 400 variables in my dataframe at once?

Thank you!

recode_mut <- function(var = "adgra2_mut", data=data_train) {
   recoded <- ifelse(data_train[[var]] == 0, 0,
                           ifelse(data_train[[var]] != 0, 1, NA))
   return(recoded)
}

recode_mut(var = "adgra2_mut")

1 Answers1

3

We can use mutate with across

library(dplyr)
out <- data_train %>%
     mutate(across(everything(), ~ as.integer(. != 0)))

Or use base R

out <- as.data.frame(+(data_train != 0))
akrun
  • 874,273
  • 37
  • 540
  • 662