0

I want to run a multinomial regression inside a function (regression_fun) and return the multinom object to work further with that.

But the summary() of the returned object does not work but gives the error: Error in stats::model.frame(formula = form, data = data_est) : object 'form' not found. Outside the function, summary() of the "same" multinom object is working fine (summary(regression_out)).

For instance, creating a glm object (regression_fun2) and returning the object, summary() works as intended.

So what is the problem here?

Reproducible code:

rm(list=ls())
library(nnet)
library(foreign)
mydata <- read.dta("https://dss.princeton.edu/training/Panel101.dta")
form01 <- as.formula("opinion ~ x1 + x2 + x3 + country")

regression_out <- multinom(formula = form01,data = mydata)
summary(regression_out)

regression_fun <- function(data_est,form){
  regression <- multinom(formula = form,data = data_est)
  return(regression)
}
regs <- regression_fun(data_est=mydata,form=form01)
summary(regs)

regression_fun2 <- function(data_est,form){
  regression <- glm(formula = form,data = data_est,family = binomial())
  return(regression)
}
form02 <- as.formula("op ~ x1 + x2 + x3 + country")
regs2 <- regression_fun2(data_est=mydata,form=form02)
summary(regs2)

Edit:

R version 4.1.0 (2021-05-18)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19044)

Matrix products: default

Random number generation:
 RNG:     Mersenne-Twister 
 Normal:  Inversion 
 Sample:  Rounding 
 
attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] foreign_0.8-81 nnet_7.3-16
sebastiann
  • 163
  • 10

1 Answers1

0

I found a solution which works but must be handled carefully. It works if the arguments of the function are assigned to the global environment. The problem is, that if you do not care you could overwrite other objects in the global environment with the same name. The solutions I found here: update() a model inside a function with local covariate did not really helped me without being to much complicated.

The updated function would be:

regression_fun <- function(data_est, form) {
  ## use the global assignment operator - but be careful not to overwrite sth in global environment
  form <<- form
  data_est <<- data_est
  regression <- multinom(formula = form, data = data_est)
  return(regression)
}

If there is still someone knows a better and not too complicated way solving this issue with the multinom object - for the glm object it works fine - it would be great to hear about.

So use carefully not to overwrite objects in the global environment!

sebastiann
  • 163
  • 10