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:
- 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?
- Is there a way to get a vector of the classes of all columns, analagous to
sapply( myDataFrame, class)
?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…