Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R programming: Find all the factors from Data Frame

Tags:

r

I am trying to get the class type of the columns of a data frame. What I am doing is:

sapply(mydata,class)

But now, I want to find only those column names which are factor. I tried the following:

sapply(data,is.factor)

But it gives me:

ResponseFlag            Gender           Marital        OccupInput
 False                   True             True            False

How can I separate column names which are factor?

Any help or idea will be appreciated.

like image 589
Mohammad Saifullah Avatar asked Oct 21 '14 10:10

Mohammad Saifullah


1 Answers

Try this:

Filter(is.factor, mydata)

names only If you just want the names:

names(Filter(is.factor, mydata))

or

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

dplyr These can alternately be expressed using dplyr like this:

library(dplyr)

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

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

mydata %>% summarise_each(funs(is.factor)) %>% unlist %>% .[.] %>% names
like image 96
G. Grothendieck Avatar answered Oct 30 '22 08:10

G. Grothendieck