Home > Software engineering >  Get the names of all factors with more than one level
Get the names of all factors with more than one level

Time:08-17

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?

CodePudding user response:

Another base R sol'n:

sapply(mtcars, \(x) nlevels(x) > 1) |> which() |> names()
# [1] "am"

Or (insipred by akrun's collapse solution):

Filter(\(x) nlevels(x) > 1, mtcars) |> names()

CodePudding user response:

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"

CodePudding user response:

In base R:

names(mtcars[, sapply(mtcars, function(x) length(levels(x))) > 1, drop = F])
#[1] "am"
  • Related