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:
class
in the environment of the data.table?sapply( myDataFrame, class)
?These seem to work in the way you want:
class(dt[[w]])
sapply(dt,class)
Also, doing 2 and then subsetting works for 1: sapply(dt,class)[w]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With