Search code examples
rmlogit

Extracting Independent variables List from a mlogit object


I am using following package:

library(mlogit)

My data is prepared as follows

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

And here is my model

testmodel <- mlogit(as.formula(Dist ~ 1|urban + unemp + tuition|1), testdata, shape='wide', choice='Dist')

Now when I run following code the result is weird

as.character(attr(testmodel$formula, 'rhs')[[2]])

> as.character(attr(testmodel$formula, 'rhs')[[2]])
[1] "+"             "urban + unemp" "tuition"    

What I expect is something like:

chr [1:3] "urban" "unemp" "tuition"     

Solution

  • You can use all.vars instead

    all.vars(testmodel$formula) # return all the variables 
    ## "Dist"    "urban"   "unemp"   "tuition"
    all.vars(testmodel$formula)[-1] # to remove the dependent variable
    [1] "urban"   "unemp"   "tuition"
    

    and with the function you have used

    all.vars(attr(testmodel$formula, 'rhs')[[2]])
    ## [1] "urban"   "unemp"   "tuition"