data.table 列的类 [英] Class of data.table column
本文介绍了data.table 列的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道如何在给定字符向量 w
的情况下确定 data.table dt
中列的类别.
I'd like to know how to ascertain the class of a column in a data.table dt
given a character vector w
.
可重现的例子:
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"
但是,将其指定为字符向量,它会返回一列 data.table:
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,")")))]
那么两个问题:
- 是否有更好(更简洁)的方法来获取单列的类(不放弃上述解决方案通过在数据环境中评估对
class
的调用所获得的速度.桌子? - 有没有办法获取所有列的类的向量,类似于
sapply(myDataFrame, class)
?
- 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:
类(dt[[w]])
sapply(dt,class)
此外,执行 2 然后对 1 进行子集化:sapply(dt,class)[w]
.
Also, doing 2 and then subsetting works for 1: sapply(dt,class)[w]
.
这篇关于data.table 列的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文