简体   繁体   中英

Transform all factor columns to the same factor

I've got the following survey data (example):

 df <- data.frame(
   Q1 = c("1 = very bad", 2, "5 = very good", 4, 3),
   Q2 = c(2, 3, "1 = very bad", "5 = very good", NA),
   Q3 = c(0.5, 2.3, 4.5, 4.6, 2), #The average of Q1 and Q2, which are 
                                  #questions of the same category
   Q4 = c("Strongly disagree", "Neutral", "Agree", "Strongly Agree", 
        "Strongly disagree")
)

But with about 350 questions and 500.000 answers. To summarize all the answers, I want all the factor columns to be in the form

  as.factor(c(1:5))

I've found out that

 levels(df$Q1) <- as.factor(c(1:5))

does the job. However, with over 300 columns, I don't want to do it manually and I can't seem to manage to do this for all columns which are a factor. I'm searching for an apply -kind of function which first recognizes a column as a factor and then changes its levels to be 1:5

Any help would be greatly appreciated, thanks in advance!

We can create an index for the factor columns, loop through the subset of dataset with lapply , specify the levels

i1 <- sapply(df, is.factor)
df[i1] <- lapply(df[i1], factor, levels = 1:5) 

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