Search code examples
rsortingfactors

How to order the level of multiple variables?


I have a dataset like that:

Sex q1 q... q10
Male Agree Strongly agree Strongly disagree
Female Desagree Agree Disagree
Male Agree Strongly agree Disagree
Female Desagree Agree Strongly disagree

I've been doing this:

df$q1 <- factor(df$q1, levels = c("Strongly disagree", "Disagree", "Agree", "Strongly agree"))
df$q2 <- factor(df$q2, levels = c("Strongly disagree", "Disagree", "Agree", "Strongly agree"))
df$qn <- factor(df$qn, levels = c("Strongly disagree", "Disagree", "Agree", "Strongly agree"))

So I'm seeking for a smart way to order these levels to all the q1:qn subset of my dataset.


Solution

  • Using dplyr::across():

    library(dplyr)
    
    df <- df %>%
      mutate(across(
        q1:q4,
        factor,
        levels = c("Strongly disagree", "Disagree", "Agree", "Strongly agree")
      ))
    
    levels(df$q3)
    # "Strongly disagree" "Disagree"          "Agree" "Strongly agree"
    

    Example data:

    set.seed(13)
    
    responses <- c("Strongly disagree", "Disagree", "Agree", "Strongly agree")
    
    df <- data.frame(
      Sex = sample(c("Male", "Female"), 5, replace = TRUE),
      q1 = sample(responses, 5, replace = TRUE),
      q2 = sample(responses, 5, replace = TRUE),
      q3 = sample(responses, 5, replace = TRUE),
      q4 = sample(responses, 5, replace = TRUE)
    )