list all factor levels of a data.frame
If your problem is specifically to output a list of all levels for a factor, then I have found a simple solution using :
unique(df$x)
For instance, for the infamous iris dataset:
unique(iris$Species)
Here are some options. We loop through the 'data' with sapply
and get the levels
of each column (assuming that all the columns are factor
class)
sapply(data, levels)
Or if we need to pipe (%>%
) it, this can be done as
library(dplyr)
data %>%
sapply(levels)
Or another option is summarise_each
from dplyr
where we specify the levels
within the funs
.
data %>%
summarise_each(funs(list(levels(.))))
Or using purrr:
data %>% purrr::map(levels)
Or to first factorize everything:
data %>% dplyr::mutate_all(as.factor) %>% purrr::map(levels)
And answering the question about how to get the lengths:
data %>% map(levels) %>% map(length)