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)
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