Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
404 views
in Technique[技术] by (71.8m points)

r - Class of data.table column

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) ?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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].


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...