Search code examples
rr-factor

Get the names of all factors with more than one level


I have example data as follows:

mtcars <- mtcars
# Creates a factor with one level
mtcars$vs <- 1
mtcars$vs <- as.factor(mtcars$vs)
# Creates a factor with 2 levels
mtcars$am <- as.factor(mtcars$am)

I would like to simply get the names of all factors with more than one level, so:

names_of_factors_with_more_lvls <- "am"

What is the shortest way to achieve this?


Solution

  • We can use nlevels to create a logical condition - use select to select the columns where it is factor class, and short circuit (&&) it with the next condition, and retreive the column names

    library(dplyr)
    mtcars %>%
       select(where(~ is.factor(.x) && nlevels(.x) > 1)) %>%
       names
    [1] "am"
    

    Slightly more compact would be

    library(collapse)
    names(gv(fact_vars(mtcars), \(x) fnlevels(x) > 1))
    [1] "am"
    

    or otherwise specify the return

    gv(fact_vars(mtcars), \(x) fnlevels(x) > 1, return = 'names')
    [1] "am"