r - 如何使用 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”不起作用。
我制作的代码只运行单个二元逻辑回归,但无法通过添加多个混杂因素进行分析。
解决方案
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
之外的所有列上运行,但您还应该排除并且因为它们包含在函数中。outcome
setdiff(names(example.data),"outcome")
bmi
age
推荐阅读
- php - 使用 Carbon 将日期保存到数据库中
- vb.net - 在焦点文本框和 DataGridView 单元格上使用虚拟键盘
- javascript - TypeError:无法读取注册页面未定义的属性“值”
- scala - 用于填充缺失值的 Spark Imputer
- pytorch - pytorch中维度的子空间是什么?
- android - Firebase 电话身份验证不发送 OTP
- clojure - 用函数概括嵌套调用 map
- java - 返回按字典顺序出现的字符串的长度
- ios - 使用 UIViewController 扩展添加/删除子视图控制器
- flutter - 获取“NoSuchMethodError:在 null 上调用了 getter 'element'。” 使用 build_runner 时