Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class of data.table column

Tags:

r

data.table

I'd like to know how to ascertain the class of a column in a data.table dt given a character vector w.

Reproducible example:

dt <- data.table(matrix(1:10, 2))
w <- "V1"

When you specify a column by name directly, it returns the vector so that you can get its class:

> dt[,V1]
[1] 1 2
> class(dt[,V1])
[1] "integer"

Specify it as a character vector, however, and it instead returns a one-column data.table:

> dt[,w,with=FALSE]
   V1
1:  1
2:  2
> class(dt[,w,with=FALSE])
[1] "data.table" "data.frame"

I've sort of munged my way to the following solution, but surely there's a better way:

dt[,eval(parse(text=paste0("class(",w,")")))]

So two questions:

  1. Is there a better (more concise) to get the class of a single column (withoout giving up the speed that the above solution gains by evaluating the call to class in the environment of the data.table?
  2. Is there a way to get a vector of the classes of all columns, analagous to sapply( myDataFrame, class) ?
like image 260
Ari B. Friedman Avatar asked Sep 16 '13 19:09

Ari B. Friedman


1 Answers

These seem to work in the way you want:

  1. class(dt[[w]])
  2. sapply(dt,class)

Also, doing 2 and then subsetting works for 1: sapply(dt,class)[w].

like image 131
Frank Avatar answered Oct 17 '22 23:10

Frank