【问题标题】:Using step with data.table将步骤与 data.table 一起使用
【发布时间】:2015-11-01 19:57:36
【问题描述】:

我能够执行以下操作:

foo=data.frame(y=rnorm(100),x1=rnorm(100),x2=rnorm(100),x3=rnorm(100))
full=lm(foo$y ~ foo$x1 + foo$x2 + foo$x3)
nil=lm(foo$y ~ 1)
fwd=step(nil,scope=list(lower=formula(nil),upper=formula(full)),direction='forward')

但我正在像这样使用 data.table:

library(data.table)
foo=data.table(y=rnorm(100),x1=rnorm(100),x2=rnorm(100),x3=rnorm(100))
full=foo[,lm(y ~ x1 + x2 + x3)]
nil=foo[,lm(y ~ 1)]
fwd=foo[,step(nil,scope=list(lower=formula(nil),upper=formula(full)),direction='forward')]

我得到了错误:

Error in eval(expr, envir, enclos) : object 'x1' not found

但是x1 是在上面的 J 表达式中为 data.table 定义的 - 有没有办法解决这个问题而不必将我的表转换为 data.frame?

【问题讨论】:

标签: r data.table lm


【解决方案1】:

您需要将.SD 作为data 参数传递给[.data.table 内的lm,否则data.table 会优化它的j 参数以仅使用引用的内容。

foo=data.table(y=rnorm(100),x1=rnorm(100),x2=rnorm(100),x3=rnorm(100))
full=foo[,lm(y ~ x1 + x2 + x3,data=.SD)]
nil=foo[,lm(y ~ 1,data=.SD)]
fwd <- step(nil,scope=list(lower=formula(nil),upper=formula(full)),direction='forward')

# using .SD means all columns are available
ls(environment(formula(nil))
## [1] "x1" "x2" "x3" "y" 

# compared with
nil.noSD =foo[,lm(y ~ 1)]
ls(environment(formula(nil.noSD)))
## [1] "y"

请注意,data.table 和 lm 以及 update.formula 等的范围规则并不总是“很好”

请参阅Why is using update on a lm inside a grouped data.table losing its model data? 了解示例

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-20
    • 2011-10-22
    • 1970-01-01
    • 1970-01-01
    • 2017-07-30
    • 1970-01-01
    • 2021-10-11
    • 1970-01-01
    相关资源
    最近更新 更多