[R] Find classes for each column of a data.frame

Erik Iverson eriki at ccbr.umn.edu
Thu Aug 26 17:37:54 CEST 2010


That's because apply works on arrays/matrices, not data.frames.

It therefore coerces your data.frame to a matrix of type
character, since you have factors, thus the result.

You want sapply or lapply, since a data.frame is actually a
list.

sapply(df, class)

and then to get what you want:

df[sapply(df, is.factor)]

Daniel Brewer wrote:
> Hello,
> 
> Is there a simple way to get the class type for each column of a
> data.frame?  I am in the situation where I would like to get all the
> columns of a data.frame that are factors.
> 
> I have tried:
> apply(df,2,class)
> but all the columns come back as class "character".
> 
> Thanks
> 
> Dan
>



More information about the R-help mailing list