【问题标题】:r Creating models on subsets with data.table inside a functionr 在函数内使用 data.table 在子集上创建模型
【发布时间】:2013-04-26 08:40:21
【问题描述】:

使用data.table,我正在尝试编写一个函数,它将数据表、公式对象和字符串作为参数,并创建和存储多个模型对象。

myData <- data.table(c("A","A","A","B","B","B"),c(1,2,1,4,5,5),c(1,1,2,5,6,4))
## This works.
ModelsbyV1 <- myData[,list(model=list(lm(V2~V3)),by=V1)]

##This does not.
SectRegress <- function (df,eq,sectors) {
  Output <- df[,list(model=list(lm(eq))),
             by=sectors]
  return(Output)
}

Test <- SectRegress(myData,formula(V2~V3),sectors="V1")
##Error in eval(expr, envir, enclos) : object 'X' not found

我已经尝试在函数中附加 df。但是,这会使按类型分组的能力无效。函数内部的 colnames(df) 包括“X”。我难住了。

【问题讨论】:

  • 我想你的意思是by=V1 in ModelsbyV1 &lt;- ...
  • 是的。我的错。谢谢!

标签: r data.table


【解决方案1】:

您必须在 .SD 环境中对其进行评估(因为 lm 不能“看到”V2 和 V3 否则):

SectRegress <- function (df,eq,sectors) {
    Output <- df[, list(model=list(lm(eq, .SD))), by=sectors]
    return(Output)
}
Test <- SectRegress(myData,formula(V2~V3),sectors="V1")

【讨论】:

  • 太棒了,你是冠军。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-08
相关资源
最近更新 更多