我在lmRob
包中使用robust
拟合多变量模型,我喜欢合适。如何使用拟合在给定点进行预测?黑客的解决方案是绘制它并在图上放置水平和垂直线以精确定位
如何为模型提供一个点,让它吐出预测?我想象的是:
predict(model, newdata = data.frame(x = 2, y = 90))
但这给了我错误:
predict(model, newdata = data.frame(x = 2, y = 90))
Error in `contrasts<-`(`*tmp*`, value = contrasts.arg[[nn]]) :
contrasts apply only to factors
traceback()
是:
> traceback()
7: stop("contrasts apply only to factors")
6: `contrasts<-`(`*tmp*`, value = contrasts.arg[[nn]])
5: model.matrix.default(delete.response(Terms), newdata, contrasts = object$contrasts,
xlevels = attr(object, "xlevels"))
4: model.matrix(delete.response(Terms), newdata, contrasts = object$contrasts,
xlevels = attr(object, "xlevels"))
3: predict.lmRob(model, newdata = data.frame(x = 1,
y = 90), interval = "predict")
2: predict(model, newdata = data.frame(x = 1, y = 90),
interval = "predict")
1: predict(model, newdata = data.frame(x = 1, y = 90),
interval = "predict")
如果我只是尝试将原始数据集传递到predict
,我会得到:
Error in x %*% coefs : non-conformable arguments
添加适当的因子级别会修复第一个警告,但会保留第二个警告。
答案 0 :(得分:4)
您需要确保newdata
与原始版本具有相同的级别,即
dat <- data.frame(x=1:10, y=factor(sample(letters[1:2], 10, rep=T)),
z=runif(10))
fit <- lmRob(z ~ ., data=dat)
## Fails, wrong factor
predict(fit, newdata=data.frame(x=11, y="a"))
## Works
predict(fit, newdata=data.frame(x=11, y=factor("a", levels=letters[1:2])))
如果您执行此类操作,您将收到第二个错误
dat <- data.frame(x=1:10, y=factor(sample(letters[1:2], 10, rep=T), levels=letters[1:3]),
z=runif(10)) # data has empty "c" level
fit <- lmRob(z ~ ., data=dat)
## Fails
predict(fit, newdata=dat)
## Works
predict(fit, newdata=droplevels(dat))