1

I know that I can use sapply to find out the class of data columns like this:

sapply(data, class)

Code above similar to: How do I get the classes of all columns in a data frame?

However, how would determine and store a vector of column names, fac that are of class factor?

Bear
  • 662
  • 1
  • 5
  • 20

2 Answers2

1

fac <- names(data)[sapply(data, is.factor)]

Bear
  • 662
  • 1
  • 5
  • 20
  • 1
    This gives you a vector, but you mentioned you want a list. You can also try `as.list(names(data)[sapply(data, is.factor)])` unless vector is what you really wanted :) – AntoniosK Sep 13 '18 at 21:50
  • @AntoniosK thank you for the catch, I meant `vector`. Corrected! – Bear Sep 13 '18 at 21:58
0

Another similar way would be to use purrr package:

names(iris)[purrr::map_lgl(iris, is.factor)]
#"Species"

which(map_lgl(iris, is.factor) == TRUE) #this will return the column index as well.
#Species 
#5 
AlexB
  • 3,061
  • 2
  • 17
  • 19