Search code examples
rscopemultinomialnnet

How do you call model.frame() on a multinom/nnet object within a function?


I'm trying to estimate a multinom() model, and then grab the model data.frame.

Outside a function, this works fine. But when I try to do so within a function, the data.frame() step throws error.

Below is sample code that should isolate the problem:

library(MASS)
library(nnet)

# create data
df <- survey
df$Exer  <- relevel(df$Exer, ref="None")    

# estimate within wrapper function -- throws error
estimator <- function(fmla, data){  
  mod1 <- multinom(fmla, data)  
  mod1$mod <- model.frame(mod1,data)
  return(mod1)
}
x <- estimator(Exer~Sex+Smoke+Age, data=df)

The last line produces this:

 Error in stats::model.frame(formula = fmla, data = data) : 
  object 'fmla' not found  

When I run traceback(), I then get this:

6: stats::model.frame(formula = fmla, data = data)
5: eval(expr, envir, enclos)
4: eval(oc, env)
3: model.frame.multinom(mod1, data)
2: model.frame(mod1, data) at #3
1: estimator(Exer ~ Sex + Smoke + Age, data = df)

Is this a scoping issue? Are there workarounds?


Solution

  • Formulas track the environment in which they are created. Not all functions behave well when formulas have different environments than the data. A possible work-around would be

    estimator <- function(fmla, data){  
      environment(fmla)<-environment()
      mod1 <- multinom(fmla, data)  
      mod1$mod <- model.frame(mod1,data)
      return(mod1)
    }
    x <- estimator(Exer~Sex+Smoke+Age, data=df)
    

    where we explicitly change the environment of the formula to the local function environment. This gives me

    # weights:  21 (12 variable)
    initial  value 258.173888 
    iter  10 value 215.870042
    final  value 215.611365 
    converged
    

    Tested with R version 3.1.2, nnet_7.3-8, and MASS_7.3-35