rdataframer-factor

list all factor levels of a data.frame


with str(data) I get the headof the levels (1-2 values)

fac1: Factor w/ 2  levels ... :
fac2: Factor w/ 5  levels ... :
fac3: Factor w/ 20 levels ... :
val: num ...

with dplyr::glimpse(data) I get more values, but no infos about number/values of factor-levels. Is there an automatic way to get all level informations of all factor vars in a data.frame? A short form with more info for

levels(data$fac1)
levels(data$fac2)
levels(data$fac3)

or more precisely a elegant version for something like

for (n in names(data))
  if (is.factor(data[[n]])) {
    print(n)
    print(levels(data[[n]]))
  }

thx Christof


Solution

  • 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(.))))