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