data.table列的类 [英] Class of data.table column
问题描述
我想知道如何确定data.table dt
中给定字符向量 w $的列的类c $ c>。
可重现的示例:
dt< - data.table(matrix(1:10,2))
w< - V1
当您直接指定列时,它会返回向量,以便您可以得到它的类:
dt [,V1]
[1] 1 2
> class(dt [,V1])$ b $ b [1]integer
一个字符向量,而是返回一列数据表:
> dt [,w,with = FALSE]
V1
1:1
2:2
> class(dt [,w,with = FALSE])
[1]data.tabledata.frame
我已经尝试了下面的解决方案,但是肯定有更好的方法:
dt [,eval(parse(text = paste0(class(,w,)))
b $ b
这两个问题:
- 有更好的(更简洁)得到单列的类通过评估在data.table环境中对
class
的调用,放弃上述解决方案获得的速度? - 一种获取所有列的类的向量的方法,类似
sapply(myDataFrame,class)
?
$ b $
-
class(dt [[w]])
-
sapply(dt,class)
另外,做2,然后子集化适用于1: sapply(dt,class)[w ]
。
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)
?
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]
.
这篇关于data.table列的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!