2

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.

1
  • I think you mean by=V1 in ModelsbyV1 <- ... Commented Apr 26, 2013 at 8:42

1 Answer 1

2

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")
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome, you are a champ. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.