[英]Error making predictions with a logistic regression model in R
I just can't figure out what is wrong with my code. 我只是不知道我的代码出了什么问题。 I fitted a logistic regression model with this dataset: 我为此数据集拟合了逻辑回归模型:
outcome predictor
1 0 -3
2 0 -4
3 1 0
4 1 -1
5 1 0
6 0 -3
I fitted this model: 我安装了这个模型:
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
Then I want to make predictions using this vector: 然后,我想使用此向量进行预测:
test
[1] -2 -5 0 -3 2 -3
predict(model, newdata = test)
And I get this error: 我得到这个错误:
Error in eval(predvars, data, env) :
numeric 'envir' arg not of length one
What is wrong? 怎么了?
If you want to use functions like predict()
you shouldn't use $
-indexing in your model; 如果要使用诸如predict()
类的函数,则不应在模型中使用$
-indexing; use the data=
argument instead, eg 使用data=
参数代替,例如
model <- glm(outcome~predictor, data=your_data, family = "binomial")
If you use $
in your formula then the predict()
function will not actually use the variables found in the new data frame . 如果您在公式中使用$
,则predict()
函数实际上将不会使用在新数据框中找到的变量 。
Using the example given: 使用给出的示例:
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
The results are the same despite using different newdata
(!). 尽管使用了不同的newdata
(!),结果还是一样的。 You'll only get a warning if you use newdata
that's a different length from your original data set. 如果你用你只会得到一个警告newdata
这是从原始数据集不同的长度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.