[R] predict() works with the design matrix but throws error with some rows of that matrix
Damir Cosic
damir.cosic at gmail.com
Fri Nov 20 04:53:25 CET 2015
Hello,
I am having problems with predict() after a multinomial logit regression by
multinom(). I generate a design matrix with model.matrix() and use it to
estimate the model. Then, if I pass the entire design matrix to predict(),
it returns the same output as fitted(), which is expected. But if I pass
only a few rows of the design matrix, it throws this error:
Error in model.frame.default(Terms, newdata, na.action = na.omit, xlev
= object$xlevels) : variable lengths differ (found for 'z') In addition:
Warning message: 'newdata' had 6 rows but variables found have 15 rows
This is a minimal example:
require(nnet)
y<-factor(rep(c(1,2,3),5), levels=1:3, labels=c("good","bad","ugly"))
x<-rnorm(15)+.2*rep(1:3,5)
z<-factor(rep(c(1,2,2),5), levels=1:2, labels=c("short","tall"))
df<-data.frame(y=y, x=x, z=z)
mm<-model.matrix(~x+z, data=df)[,2:3]
m<-multinom(y ~ x+z, data=df)
p1<-predict(m,mm,"probs")
p2<-predict(m,head(mm),"probs")
My actual goal is out-of-sample prediction, but I could not make it work
and, while debugging it, I reduced it to this problem.
Best,
Damir
[[alternative HTML version deleted]]
More information about the R-help
mailing list