2

I know this question has been raised before (Error in <my code> : object of type 'closure' is not subsettable). But I could not get my head around it.

Here is the packages I use and how I prepare my data

library(mlogit)

data(CollegeDistance, package="AER")
Data <- CollegeDistance 
Data$Dist[Data$distance<0.4] <- 1
Data$Dist[Data$distance<1 & Data$distance>=0.4] <- 2
Data$Dist[Data$distance<2.5 & Data$distance>=1] <- 3
Data$Dist[Data$distance>=2.5] <- 4

Now when I define a mlogit object and use it for prediction I get that error.

Formula <- paste('Dist ~', paste('1|',paste(c("urban", "unemp", "tuition"), collapse = " + "),'|1')) 
Model <- mlogit(as.formula(Formula), Data, shape='wide', choice='Dist')

Predict <- predict(Model, newdata=mlogit.data(Data, shape='wide', choice='Dist'), returnData=FALSE)

The interesting part is that if I replace Formula with formulathen it works!

UPDATE

I encounter that problem while using mlogit in a function. I really appreciate it if you can show me a way out of it.

modelmaker <- function(variables){
  Formula <- paste('Dist ~', paste('1|',paste(variables, collapse = " + "),'|1'))
  MODEL <- mlogit(as.formula(Formula), Data, shape='wide', choice='Dist')  
  return(MODEL)
}

Model <- modelmaker(c("urban", "unemp", "tuition"))
Predict <- predict(Model, newdata=mlogit.data(Data, shape='wide', choice='Dist'), returnData=FALSE)

This time is does not solve even by avoiding using formula or Formula. If you change it to XXX the error will be

object 'XXX' not found
Community
  • 1
  • 1
Milad
  • 339
  • 2
  • 12
  • related: https://stat.ethz.ch/pipermail/r-devel/2015-March/070887.html and following thread ... – Ben Bolker Apr 06 '15 at 23:13
  • I bet it's getting mad because `Formula()` is a function in the `Formula` package required by `mlogit`... – alexforrence Apr 06 '15 at 23:19
  • 3
    this could have been avoided by not calling your formula either `Formula` or `formula` or your dog `dog`, `fortunes::fortune(77)` – rawr Apr 06 '15 at 23:20
  • @alexforrence, your hypothesis seems to be correct. Replacing `Formula` with `Formula1` above makes it work. It would take too much digging through the guts for me to figure out precisely what's going on though ... – Ben Bolker Apr 06 '15 at 23:23
  • @rawr, fair enough, but I wouldn't have known easily that I needed to avoid `Formula` as well as `formula` ... – Ben Bolker Apr 06 '15 at 23:23
  • @BenBolker sure. I am still wondering why `mlogit:::predict.mlogit` finds `Formula::Formula` before `Formula` in `as.environment(1)`, maybe that is in your thread – rawr Apr 06 '15 at 23:27

0 Answers0