Home > Mobile >  Recoding multiple adjacent columns so that 1=1, otherwise=0
Recoding multiple adjacent columns so that 1=1, otherwise=0

Time:01-04

Not having luck with the simple task of recoding 19 contiguous variables (columns) such that 1=1 otherwise=0 (i.e., any other value becomes zero). The 19 variables are s40b.1:s40b.19. Here's what I've tried...

df %>% 
mutate_at(vars(c(s40b.1:s40b.19), function(x) {
    case_when(
      x ==1 ~ 1,
      x != 1 ~ 0)
  })

CodePudding user response:

You should be able to use lapply() if you want a base R approach - since I dont have your exact data I made some sample data, though not sure if it is generally the same as what you have.

## Create sample data
sample_data <- data.frame(id = sample(LETTERS, 50, replace = TRUE),
                          c1 <- sample(1:10, 50, replace = TRUE),
                          c2 <- sample(1:10, 50, replace = TRUE),
                          c3 <- sample(1:10, 50, replace = TRUE),
                          c4 <- sample(1:10, 50, replace = TRUE),
                          c5 <- sample(1:10, 50, replace = TRUE),
                          c6 <- sample(1:10, 50, replace = TRUE),
                          c7 <- sample(1:10, 50, replace = TRUE),
                          c8 <- sample(1:10, 50, replace = TRUE),
                          c9 <- sample(1:10, 50, replace = TRUE),
                          c10 <- sample(1:10, 50, replace = TRUE),
                          c11 <- sample(1:10, 50, replace = TRUE),
                          c12 <- sample(1:10, 50, replace = TRUE),
                          c13 <- sample(1:10, 50, replace = TRUE),
                          c14 <- sample(1:10, 50, replace = TRUE),
                          c15 <- sample(1:10, 50, replace = TRUE),
                          c16 <- sample(1:10, 50, replace = TRUE),
                          c17 <- sample(1:10, 50, replace = TRUE),
                          c18 <- sample(1:10, 50, replace = TRUE),
                          c19 <- sample(1:10, 50, replace = TRUE))
cols <- sprintf("s40b.%s",seq(1:19))
names(sample_data)[2:20] <- cols

To convert the columns s40b.1 to s40b.19 using lapply():

cols <- sprintf("s40b.%s",seq(1:19))

sample_data[cols] <- lapply(sample_data[cols], function(x){ifelse(x != 1, 0, 1)})

CodePudding user response:

maybe something like this...



df_new<-df %>%
  mutate(across(contains("s40b"), ~if_else(.x==1, 1, 0)))
  •  Tags:  
  • Related