简体   繁体   中英

R Use factor() for nominal data - how to value labels for multiple variables

I'm an R newbie so this problem is probably quite obvious but I have had a good search around and can't find anything.

I'm wanting to use R to analyse a survey rather than the usual method excel.

I have my variables labeled as Q1, Q2, Q3...

Q1 and Q2 contains nominal data (1, 2) and I'd like the values replacing with ("Yes", "No"). I can do this for Q1 using the code below but I'm not sure if I should subset or use c( to use the factor function. The survey will have about 25 questions this will need applying to so I'd rather it be done in one line of code rather than 25.

resdata$Q1 <- factor(resdata$Q1, levels = c(1,2), labels = c("Yes", "No"))

First you need to define the replacer function:

repl.f <- function(x) ifelse(x==1, "Yes","No")

Then simply use this argument in mutate_each() in dplyr:

library(dplyr)
resdata <- resdata %>% mutate_each(funs(repl.f),contains("Q"))

Its first argument is the functions you want to apply inside funs(), the second is the subset of columns. If you only give it one function, then it will by default replace these columns. To select the columns you can use another dplyr function:contains(), which much like everything else in dplyr speaks for itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM