0

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

添加适当的因子水平会修复第一个警告,但会留下第二个警告。

4

1 回答 1

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))
于 2015-08-10T20:51:56.803 回答