How to use predict with multinom() with intercept in R?

喜欢而已 提交于 2019-12-10 10:39:14

问题


I have run the multinom() function in R, but when I try to predict on a new sample, it keeps giving an error.

this is the code:

library(nnet)
dta=data.frame(replicate(10,runif(10)))
names(dta)=c('y',paste0('x',1:9))
res4 <- multinom(y ~ as.matrix(dta[2:10]) , data=dta)
#make new data to predict
nd<-0.1*dta[1,2:10]
pred<-predict(res4, newdata=nd)

and this is the error:

Error in predict.multinom(res4, newdata = nd) : 
  NAs are not allowed in subscripted assignments

I think it has to do with the intercept being included in the analysis, but not in the new prediction input. I tried to set it manually by merging a 1x1 data frame containing a 1 named "Intercept" (as it is called in the summary()), but it still gives the same error.

#add intercept manually to prediction row
intercept<-data.frame(1)
names(intercept)[1]<-"Intercept"
nd<-merge(intercept,nd)

回答1:


The problem is with how you specified your model: you can't mix R functions into formulas like that. Try this:

res4 <- multinom(y ~ . , data=dta) # You could also specify explicitly: y~x1+x2+x3...
#make new data to predict
nd<-0.1*dta[1,2:10]
predict(res4, newdata=nd)
# [1] 0.971794712357223
# 10 Levels: 0.201776991132647 0.211950202938169 0.223103292752057 0.225121688563377 0.372682225191966 0.612373929005116 ... 0.971794712357223


来源:https://stackoverflow.com/questions/21663945/how-to-use-predict-with-multinom-with-intercept-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!