Home > Software engineering >  Select columns by pattern and replace factor at once
Select columns by pattern and replace factor at once

Time:10-25

I have a data frame with several columns. Some of the columns have fixed patterns at the beginning for example q1a, q1a_30, q1a_60, q1a_90. I want to call the columns with the same begging pattern and replace their factors.

Process I can do it separately, for each stage but is there any way to do it at once? Here is as far what I have done:

df[,grepl("q1a", colnames(df))]
df$q1a<- recode_factor(df$q1a, `1` = "Yes", `2` = "No",`3` = "I don't know",`4` = "Maybe")

CodePudding user response:

If you determine which columns to recode based on your determined pattern:

my_col <- grep("q1a", names(df))

You can use lapply for those columns to recode your factors:

df[, my_col] <- lapply(df[, my_col], function(x) {
  recode_factor(x, `1` = "Yes", `2` = "No", `3` = "I don't know", `4` = "Maybe")
})

Please let me know if this is what you had in mind.

CodePudding user response:

We may use tidyverse

library(dplyr)
df %>%
    mutate(across(starts_with('q1a'), 
    ~ recode_factor(., `1` = "Yes", `2` = "No",
           `3` = "I don't know",`4` = "Maybe")))
  • Related