在 R 中绘制逻辑回归的预测线

时间:2021-04-07 03:46:03

标签: r logistic-regression

我在 R 中建立了逻辑回归模型并成功绘制了模型的点以显示数据集中的关系。我无法显示预测的折线图。该模型根据初始住院时间(以天为单位)预测医院的再入院率。这是我的代码:

mydata <- read.csv(file = 'C:\\Users\\nickg\\Downloads\\3kfid8emf9rkc9ek30sf\\medical_clean.csv', header=TRUE)[,c("Initial_days","ReAdmis")]
head(mydata)
mydata$ReAdmis.f <- factor(mydata$ReAdmis)
logfit <- glm(mydata$ReAdmis.f ~ mydata$Initial_days, data = mydata, family = binomial)
summary(logfit)
range(mydata$Initial_days)
xweight <- seq(0, 79.992, .008)
yweight <- predict(logfit, list(xweight),  type = "response")
plot(mydata$Initial_days, mydata$ReAdmis.f, pch = 16, xlab = "Initial Days", ylab = "ReAdmission Y/N")
lines(xweight, yweight)

如您所见,我已经设置了模型以及 xweight 和 yweight 描述的范围,但该行没有显示任何内容。

1 个答案:

答案 0 :(得分:1)

始终使用 curve

plot(ReAdmis.f ~ Initial_days, data = mydata, 
     pch = 16, xlab = "Initial Days", ylab = "ReAdmission Y/N")

curve(predict(logfit, newdata = data.frame(Initial_days = x), 
#x is created by the curve function based on the plot's x limits 
#note that newdata must contain the x variable with exactly the same name as in the original data
              type = "response"),
      add = TRUE)

然而,这里的问题可能是您的 y 变量是一个因子变量(如果您有两个级别,则内部值为 1 和 2),而逻辑回归预测始终在区间 [0, 1] 中。在运行代码之前,您应该将 ReAdmis.f 转换为 0/1 整数值。