R 收集data.table下的系数级别,with=FALSE

R 收集data.table下的系数级别,with=FALSE,r,reference,functional-programming,data.table,R,Reference,Functional Programming,Data.table,这在数据中。表1.9.4 上下文 我在函数调用中结束了一个ML训练操作,我想获得传入的data.table列的级别。我注意到,这要求使用get()取消列参数的引号: 演示失败方法的一个简单示例: library(data.table) test.table <- data.table(col1 = rep(c(0,1), times = 10), col2 = 1:20) col.id <- "col1" str(test.table[,levels(col.id),with=FA

这在
数据中。表
1.9.4

上下文 我在函数调用中结束了一个ML训练操作,我想获得传入的
data.table
列的级别。我注意到,这要求使用
get()
取消列参数的引号:

演示失败方法的一个简单示例:

library(data.table)
test.table <- data.table(col1 = rep(c(0,1), times = 10), col2 = 1:20)
col.id <- "col1"

str(test.table[,levels(col.id),with=FALSE])

Classes ‘data.table’ and 'data.frame':  0 obs. of  0 variables
 - attr(*, ".internal.selfref")=<externalptr>

> str(test.table[,levels(factor(col.id)), with=FALSE])
Classes ‘data.table’ and 'data.frame':  20 obs. of  1 variable:
 $ col1: num  0 1 0 1 0 1 0 1 0 1 ...
 - attr(*, ".internal.selfref")=<externalptr>

> str(test.table[,levels(as.factor(col.id)), with=FALSE])
Classes ‘data.table’ and 'data.frame':  20 obs. of  1 variable:
 $ col1: num  0 1 0 1 0 1 0 1 0 1 ...
 - attr(*, ".internal.selfref")=<externalptr>

levels(test.table[,factor(col.id), with=FALSE])
NULL

levels(test.table[,as.factor(col.id), with=FALSE])
NULL

为什么会这样?它是有意的吗?

我们如何知道您是在引用data.table框架内的列,还是正在使用的变量中存储的列?假设在
data.table
中有一个名为
col.id
的列。我们怎么决定你要哪一个?没错。我已经非常习惯R和
数据。表
为我做正确的事情;)
eval(as.name(col.id))
可能比
get
更有效,您也可以尝试
.SD[[col.id]]
。为了可读性和简单性,我一直使用
get
。我对
eval
deparse
等方面不够聪明。然而
.SD[[target]]
是惯用的方式,但它还没有得到优化不幸的是,你可以责怪Arun:)
> test.table[,levels(as.factor(get(col.id)))]
[1] "0" "1"
> test.table[,levels(as.factor(get(col.id)))]
[1] "0" "1"
> test.table[,levels(factor(get(col.id)))]
[1] "0" "1"
> levels(test.table[,factor(get(col.id))])
[1] "0" "1"