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,
NA))))
}
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!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…