R: find all factors from Data Frame

I am trying to get the type of a dataframe column class. I'm doing it:

sapply(mydata,class)

      

But now I want to find only those column names that are factors. I tried the following:

sapply(data,is.factor)

      

But this gives me:

ResponseFlag            Gender           Marital        OccupInput
 False                   True             True            False

      

How can I separate the column names that are factors?

Any help or idea would be appreciated.

+3


source to share


1 answer


Try the following:

Filter(is.factor, mydata)

      

names only If you just want names:

names(Filter(is.factor, mydata))

      



or

names(iris)[ sapply(iris, is.factor) ]

      

dplyr They can be expressed alternately with dplyr as follows:

library(dplyr)

mydata %>% Filter(f = is.factor)

mydata %>% Filter(f = is.factor) %>% names

mydata %>% summarise_each(funs(is.factor)) %>% unlist %>% .[.] %>% names

      

+9


source







All Articles