【问题标题】:Graphing prediction line of a logistic regression in R在 R 中绘制逻辑回归的预测线
【发布时间】:2021-04-07 03:46:03
【问题描述】:

我已经在 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 描述的模型和范围,但该行没有显示任何内容。

【问题讨论】:

  • 如果您包含一个简单的reproducible example,其中包含可用于测试和验证可能解决方案的示例输入和所需输出,则更容易为您提供帮助。也许试试lines(xweight, yweight + 1)。如果不能运行和测试看看发生了什么,很难说。

标签: r logistic-regression


【解决方案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 整数值。

【讨论】:

  • 感谢您的回答,我继续将文件中的 Readmis 的值更改为 1 和 0 以表示是和否,然后删除了“因子”函数。当我尝试您的解决方案时,我收到此错误:Error in curve(predict(logfit, newdata = data.frame(Initial_days = x), : 'expr' did not evaluate to an object of length 'n' In addition: Warning message: 'newdata' had 101 rows but variables found have 10000 rows
  • 请参阅我的回答中评论的第二行。为了使它起作用,您不能在模型公式中使用$。由于您也不需要在模型公式中使用$logfit &lt;- glm(ReAdmis.f ~ Initial_days, data = mydata, family = binomial)
猜你喜欢
  • 1970-01-01
  • 2021-02-27
  • 2016-08-09
  • 2014-04-22
  • 1970-01-01
  • 1970-01-01
  • 2021-11-23
  • 1970-01-01
  • 2018-10-13
相关资源
最近更新 更多