首页 > 解决方案 > 如何使用 R 中的 glm 在二元逻辑回归中创建循环以包含混杂因素(协变量)?

问题描述

有超过 50 个暴露变量,总共 16,000 个数据。
我需要分析所有暴露变量和结果之间的关联。

我想重复以下公式。

example.data <- data.frame(outcome = c(0,0,0,1,0,1,0,0,1,0),
                           exposure_1 = c(2.03, 2.13, 0.15, -0.14, 0.32,2.03, 2.13, 0.15, -0.14, 0.32),
                           exposure_2 = c(-0.11, 0.93, -1.26, -0.95, 0.24,-0.11, 0.93, -1.26, -0.95, 0.24),
                           age = c(20, 25, 30, 35, 40, 50, 55, 60, 65, 70),
                           bmi = c(20, 23, 21, 20, 25, 18, 20, 25, 26, 27))

logit_1 <- glm(outcome ~exposure_1, family = binomial, data = example.data)
logit_2 <- glm(outcome~ exposure_2 + age+ bmi, family = binomial, data = example.data)

我做了一个这样的公式。

Model1 <- function(x) {
  temp <- glm(reformulate(x,response="outcome"), data=example.data, family=binomial)
  c(exp(summary(temp)$coefficients[2,1]), # OR
    exp(confint(temp)[2,1]), # CI 2.5 
    exp(confint(temp)[2,2]), # CI 97.5
    summary(temp)$coefficients[2,4], # P-value
    colAUC(predict(temp, type = "response"),example.data$outcome)) #AUC
Model1.data <- as.data.frame(t(sapply(setdiff(names(example.data),"outcome"), Model1)))
}

Model2 <- function(x) {
  temp <- glm(reformulate(x + age + bmi, response="outcome"), data=example.data, family=binomial)
  c(exp(summary(temp)$coefficients[2,1]), # OR
    exp(confint(temp)[2,1]), # CI 2.5 
    exp(confint(temp)[2,2]), # CI 97.5
    summary(temp)$coefficients[2,4], # P-value
    colAUC(predict(temp, type = "response"),example.data$outcome)) #AUC
}
Model2.data <- as.data.frame(t(sapply(setdiff(names(example.data),"outcome"), Model2)))

但是,功能“Model2”不起作用。
我制作的代码只运行单个二元逻辑回归,但无法通过添加多个混杂因素进行分析。

标签: rloopsassociationsglm

解决方案


c()不使用+reformulate. 在您的两个函数中,x都采用列名的值。我将使用mtcars列名来说明:

## Model1 works
reformulate("hp", response = "mpg")
# mpg ~ hp

## Model2 doesn't work
reformulate("hp" + wt + cyl, response = "mpg")
# Error in reformulate("hp" + wt + cyl, response = "mpg") : 
#   object 'wt' not found

## Fix it with `c()` and quoted column names
reformulate(c("hp", "wt", "cyl"), response = "mpg")
# mpg ~ hp + wt + cyl

## Showing it works with a mix of variables and quoted column names
x = "hp"
reformulate(c(x, "wt", "cyl"), response = "mpg")
# mpg ~ hp + wt + cyl

所以在你的Model2,改变为reformulate(c(x, "age", "bmi"), response="outcome")

您还有其他问题 - 您正在除( )Model2之外的所有列上运行,但您还应该排除并且因为它们包含在函数中。outcomesetdiff(names(example.data),"outcome")bmiage


推荐阅读