如何在带有R的拦截的multinom()中使用预测? [英] How to use predict with multinom() with intercept in R?

查看:266
本文介绍了如何在带有R的拦截的multinom()中使用预测?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在R中运行了multinom()函数,但是当我尝试对一个新样本进行预测时,它会不断出现错误.

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

这是代码:

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)

这是错误:

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

我认为这与分析中包含的截距有关,但与新的预测输入无关.我尝试通过合并包含名为1的"Intercept"(如在summary()中调用)的1x1数据帧来手动设置它,但仍然会出现相同的错误.

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)

推荐答案

问题在于如何指定模型:您不能将R函数混入这样的公式中.试试这个:

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

这篇关于如何在带有R的拦截的multinom()中使用预测?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆