在 R 中绘制多元逻辑回归模型的结果 [英] Plot the results of a multivariate logistic regression model in R

查看:109
本文介绍了在 R 中绘制多元逻辑回归模型的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想绘制多变量逻辑回归分析 (GLM) 的结果,用于调整特定自变量(即独立于模型中包含的混杂因素)与结果(二进制)的关系.

I would like to plot the results of a multivariate logistic regression analysis (GLM) for a specific independent variables adjusted (i.e. independent of the confounders included in the model) relationship with the outcome (binary).

我看到一些帖子推荐使用 predict 命令后跟 curve 的以下方法,这是一个例子;

I have seen posts that recommend the following method using the predict command followed by curve, here's an example;

x     <- data.frame(binary.outcome, cont.exposure)
model <- glm(binary.outcome ~ cont.exposure, family=binomial, data=x)
plot(cont.exposure, binary.outcome, xlab="Temperature",ylab="Probability of Response") 
curve(predict(model, data.frame(cont.exposure=x), type="resp"), add=TRUE, col="red")

然而,这似乎不适用于多元回归模型.当我添加年龄"(任意 - 可以是任何相同长度的变量)作为混淆变量时,出现以下错误;

However this does not seem to work for multivariate regression models. I get the following error when I add 'age' (arbitrary - could be any variable of same length) as a confounding variable;

> x     <- data.frame(binary.outcome, cont.exposure, age)
> model <- glm(binary.outcome ~ cont.exposure + age, family=binomial, data=x)
> plot(cont.exposure, binary.outcome, xlab="Temperature",ylab="Probability of Response") 
> curve(predict(model, data.frame(cont.exposure=x), type="resp"), add=TRUE, col="red")
Error in model.frame.default(Terms, newdata, na.action = na.action, xlev = object$xlevels) : 
  variable lengths differ (found for 'age')
In addition: Warning message:
  'newdata' had 101 rows but variable(s) found have 698 rows 

<小时>

以上模型是我想运行的模型的简化版,但原理是一样的;我想绘制二元结果变量与连续暴露之间的关系,独立于混杂因素..

如果能找到解决上述问题的方法,或者以另一种方式查看我感兴趣的关系,那就太好了.非常感谢.

It would be great to get either a workaround for the above, or an alternative way to view the relationship I am interested in. Many thanks.

推荐答案

set.seed(12345)
dataset <- expand.grid(Temp = rnorm(30), Age = runif(10))
dataset$Truth <- with(dataset, plogis(2 * Temp - 3 * Age))
dataset$Sample <- rbinom(nrow(dataset), size = 1, prob = dataset$Truth)
model <- glm(Sample ~ Temp + Age, data = dataset, family = binomial)
newdata <- expand.grid(
  Temp = pretty(dataset$Temp, 20), 
  Age = pretty(dataset$Age, 5))
newdata$Sample <- predict(model, newdata = newdata, type = "response")
library(ggplot2)
ggplot(newdata, aes(x = Temp, y = Sample)) + geom_line() + facet_wrap(~Age)

ggplot(newdata, aes(x = Temp, y = Sample, colour = Age, group = Age)) + 
  geom_line()

这篇关于在 R 中绘制多元逻辑回归模型的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆