Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others


0 votes
in Technique[技术] by (71.8m points)

How do I recode several columns by name in R in a "tidyverse" way?

I have several columns in a data frame that I'm trying to recode and would like to do it in a way that's more elegant than I'm currently doing.

Here's my data frame:

df <- data.frame(name=c("Joe","Bob","Sue","Tim", "Steve"), 
                 X1=c("Always", "Sometimes", "Often", "Never", NA), 
                 X2=c("Yes", "No", "No", "Yes", "Yes"),
                 X3=c("Sometimes", "Sometimes", "Never", "Always", "Always"))
name    X1          X2    X3
Joe     Always      Yes   Sometimes
Bob     Sometimes   No    Sometimes
Sue     Often       No    Never
Tim     Never       Yes   Always
Steve   NA          Yes   Always

My current method of recoding is quite inelegant:

for(i in c(2, 4)){
  df[,paste(colnames(df), '_recode', sep="")[i]] = ifelse(df[,i] == 'Always', 1, 
                                                                                  ifelse(df[,i] == 'Often', 2,
                                                                                         ifelse(df[,i] == 'Sometimes', 3,
                                                                                                ifelse(df[,i] == 'Never', 4,

I'd like to be able to reference the columns by name instead of by index so that the code is more stable. I'd also like to do this in tidyverse if possible. Thanks!

Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

We can use mutate with across

df1 <- df %>%
      mutate(across(c(2, 4),  ~ setNames(1:4, c("Always", "Often", 
         "Sometimes", "Never"))[.], .names = "{.col}_recode"))


#   name        X1  X2        X3 X1_recode X3_recode
#1   Joe    Always Yes Sometimes         1         3
#2   Bob Sometimes  No Sometimes         3         3
#3   Sue     Often  No     Never         2         4
#4   Tim     Never Yes    Always         4         1
#5 Steve      <NA> Yes    Always        NA         1

Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share