r在函数内部使用data.table创建子集上的模型 [英] r Creating models on subsets with data.table inside a function

查看:78
本文介绍了r在函数内部使用data.table创建子集上的模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用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))
##这样工作。
ModelsbyV1< - myData [,list(model = list(lm(V2〜V3)),by = V1)]

##这不是。
SectRegress< - function(df,eq,sectors){
Output< - df [,list(model = list(lm(eq))),
by = sectors]
return(Output)
}

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

功能。但是,这会使按类型分组的能力无效。函数中的列名(df)包含X。我被骗了。

解决方案

您必须在环境中评估 .SD lm 无法看到V2和V3):

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

Using data.table, I am trying to write a function that takes a data table, a formula object, and a string as arguments, and creates and stores multiple model objects.

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

I have tried ataching the df in the function. But, that nullifies the ability to group by type. The colnames(df) inside the function includes "X". I'm stumped.

解决方案

You've to evaluate it within the environment .SD (as lm can not "see" V2 and V3 otherwise):

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")

这篇关于r在函数内部使用data.table创建子集上的模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆