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

Marc Schwartz marc_schwartz at me.com
Thu Aug 26 17:44:18 CEST 2010


On Aug 26, 2010, at 10:36 AM, David Winsemius wrote:

> 
> On Aug 26, 2010, at 11:31 AM, 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)
> 
> lapply(df, class)
> 
>> but all the columns come back as class "character".
> 
> Agree that is not what I would have expected.


> sapply(iris, class)
Sepal.Length  Sepal.Width Petal.Length  Petal.Width      Species 
   "numeric"    "numeric"    "numeric"    "numeric"     "factor" 


> apply(iris, 2, class)
Sepal.Length  Sepal.Width Petal.Length  Petal.Width      Species 
 "character"  "character"  "character"  "character"  "character" 


The second occurs because apply() will coerce the data frame to a matrix:


> str(as.matrix(iris))
 chr [1:150, 1:5] "5.1" "4.9" "4.7" "4.6" "5.0" "5.4" ...
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr [1:5] "Sepal.Length" "Sepal.Width" "Petal.Length" "Petal.Width" ...

Since a matrix can only contain a single class of objects (recall that a matrix is a vector with dim attributes), 'iris' becomes a character matrix.

HTH,

Marc Schwartz



More information about the R-help mailing list