mgriebe
mgriebe

Reputation: 908

r Creating models on subsets with data.table inside a function

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.

Upvotes: 2

Views: 570

Answers (1)

Arun
Arun

Reputation: 118799

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

Upvotes: 2

Related Questions