[英]How do I include GLM in a loop in R
My GLM models works fine, but in order to speed things up I want to include the variable names in a loop and make R calculate the GLM for each variable. 我的GLM模型工作正常,但是为了加快速度,我想在循环中包含变量名称,并让R为每个变量计算GLM。 So I tried this:
所以我尝试了这个:
varlist <- c("age", "doc")
for (i in 1:length(varlist))
{
glmmodel <- glm(formula = Kommunikation ~ varlist[i], family = binomial, data = analysis_data)
univars[i,1] <- names(coef(glmmodel))[2]
univars[i,2] <- exp(confint.default(glmmodel)[2,1])
univars[i,3] <- exp(glmmodel$coefficients[2])
univars[i,4] <- exp(confint.default(glmmodel)[2,2])
}
Unfortunately, this results in the error: 不幸的是,这导致错误:
Error in model.frame.default(formula = Kommunikation ~ varlist[[i]], data = analysis_data, :
variable lengths differ (found for 'varlist[[i]]')
As the GLM model works when I substitute varlist[i]
with the respective variable names age
and doc
, I would guess the issue stems from how the characters are read by R when substituting the variable name? 当我用变量名
age
和doc
替换varlist[i]
时,GLM模型起作用了,我猜这可能是由R替换变量名时如何读取字符引起的? (I have 26 variables but posting two only for convenience.) (我有26个变量,但仅出于方便而发布了两个。)
The problem is that you're trying to drop a string into your formula in your call to glm()
. 问题是您要在对
glm()
调用中将字符串放入公式中。 Here's one possible solution in which you pass the string to a call to as.formula
and then use that formula in the model instead. 这是一个可能的解决方案,其中将字符串传递给对
as.formula
的调用,然后在模型中使用该公式。
df <- data.frame(y = rbinom(10, 1, 0.5), x1 = rnorm(10), x2 = rnorm(10))
varlist <- c("x1", "x2")
univars <- data.frame() # create an empty data frame so the rest of your code works
for (i in seq_along(varlist))
{
mod <- as.formula(sprintf("y ~ %s", varlist[i]))
glmmodel <- glm(formula = mod, family = binomial, data = df)
univars[i,1] <- names(coef(glmmodel))[2]
univars[i,2] <- exp(confint.default(glmmodel)[2,1])
univars[i,3] <- exp(glmmodel$coefficients[2])
univars[i,4] <- exp(confint.default(glmmodel)[2,2])
}
Result: 结果:
> univars
V1 V2 V3 V4
1 x1 0.4728192 3.1185658 20.569074
2 x2 0.1665581 0.7241709 3.148592
Also, I would be inclined to do this with lapply
instead of a for
loop, making rows that you can then bind. 另外,我倾向于使用
lapply
而不是for
循环来执行此操作,从而创建可以绑定的行。 But this works. 但这有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.