Pages

Quickly Find the Class of data.frame vectors in R

Aviad Klein over at My ContRibution wrote a convenient R function to list the classes of all the vectors that make up a data.frame. You would think apply(kyphosis,2,class) would do the job but it doesn't - it calls every vector a character class. Aviad wrote an elegant little function that does the job perfectly without having to load any external package:  

allClass<-function(x) {unlist(lapply(unclass(x),class))}.

Here it is in action:

> # load the CO2 dataset
> data(CO2)
>
> # look at the first few rows
> head(CO2)
  Plant   Type  Treatment conc uptake
1   Qn1 Quebec nonchilled   95   16.0
2   Qn1 Quebec nonchilled  175   30.4
3   Qn1 Quebec nonchilled  250   34.8
4   Qn1 Quebec nonchilled  350   37.2
5   Qn1 Quebec nonchilled  500   35.3
6   Qn1 Quebec nonchilled  675   39.2
>
> # this doesn't work
> apply(CO2,2,class)
      Plant        Type   Treatment        conc      uptake
"character" "character" "character" "character" "character"
>
> # this does
> allClass <- function(x) {unlist(lapply(unclass(x),class))}
>
> allClass(CO2)
   Plant1    Plant2      Type Treatment      conc    uptake
"ordered"  "factor"  "factor"  "factor" "numeric" "numeric"

Nice tip, Aviad.