Tom
Tom

Reputation: 2351

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?

Upvotes: 2

Views: 68

Answers (3)

akrun
akrun

Reputation: 887511

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"

Upvotes: 2

s_baldur
s_baldur

Reputation: 33538

Another base R sol'n:

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

Or

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

Upvotes: 4

Ma&#235;l
Ma&#235;l

Reputation: 52209

In base R:

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

Upvotes: 3

Related Questions