使用R中的逻辑回归模型进行预测时出错

时间:2017-03-12 21:19:39

标签: r error-handling logistic-regression

我无法弄清楚我的代码有什么问题。我在这个数据集中安装了逻辑回归模型:

foo({uid: 'LBL_btBeZETZ', label: 'bar'})

我适合这个模型:

  outcome predictor
1       0        -3 
2       0        -4
3       1         0
4       1        -1
5       1         0
6       0        -3

然后我想用这个载体进行预测:

model <- glm(data$outcome~data$predictor, family = "binomial")

               Estimate Std. Error    z value     Pr(>|z|)
(Intercept) -0.01437719 0.07516923 -0.1912644 8.483185e-01
pvalue.us    0.19469804 0.03110934  6.2585081 3.886777e-10

我收到了这个错误:

test
[1] -2 -5  0 -3  2 -3

predict(model, newdata = test)

有什么问题?

1 个答案:

答案 0 :(得分:2)

如果您想使用predict()等功能,则不应使用$ - 在模型中建立索引;改为使用data=参数,例如

 model <- glm(outcome~predictor, data=your_data, family = "binomial")

如果您在公式中使用$,则predict()函数实际上不会使用新数据框中找到的变量

使用给出的例子:

 model <- glm(data$outcome~data$predictor, family = "binomial")
 predict(model,newdata=data.frame(predictor=1:6))
 ##         1         2         3         4         5         6 
 ## -23.48969 -46.57791  45.77497  22.68675  45.77497 -23.48969
 predict(model,newdata=data.frame(predictor=rep(0,6)))
 ##         1         2         3         4         5         6 
 ## -23.48969 -46.57791  45.77497  22.68675  45.77497 -23.48969 

尽管使用了不同的newdata(!),结果仍然相同。如果您使用的newdata与原始数据集的长度不同,则只会收到警告。

相关问题