Search code examples
rcategorical-data

Reorder the levels of multiple categorical variables using a vector of variable names


I have a large dataset with factor variables but would like to only reorder the levels of a list of variables, titled "myvars" below. I want to reorder the levels for the purposes of summarizing them in a way that makes sense in a table 1. However when I try to change the order of the levels of the entire vector of variables in my dataset, I keep getting an error: Error: Assigned data value must be compatible with existing data...

Sample data:

donuts <- c("moderately","a lot","a lot","a lot","a little bit")
cookies <- c("a lot","a lot","not at all","moderately","a lot")
cupcakes <- c("not at all","not at all","a lot","moderately","a little bit")
coffee <- c("a little bit","not at all","moderately","a little bit","not at all")
macarons <- c("a little bit","moderately","not at all","not at all","a little bit")
dataset <- as.data.frame(donuts,cookies,cupcakes,coffee,macarons)
myvars <- c("donuts","cookies","cupcakes")

dataset[,myvars] <- factor(dataset[,myvars],levels=c("Not at all","Moderately","A little bit","A lot"))

Or should I use a loop? Any advice is much appreciated, thank you!


Solution

  • Use lapply to to change factor levels in multiple columns. Also make sure that factor levels are same as in your data, otherwise it would return NA. In your attempt you are using mixed upper and lower case whereas in your data it is only lower case.

    dataset[, myvars] <- lapply(dataset[, myvars], factor, 
                          levels=c("not at all","moderately","a little bit","a lot"))
    

    Using dplyr :

    library(dplyr)
    dataset %>%
      mutate(across(myvars, factor, 
                   levels=c("not at all","moderately","a little bit","a lot")))
      #In older version of dplyr use mutate_at
      #mutate_at(vars(myvars), factor, 
                   levels=c("not at all","moderately","a little bit","a lot"))
    

    data

    dataset <- data.frame(donuts,cookies,cupcakes,coffee,macarons)