[英]Loop over data table columns and apply glm using for loop
I am trying to loop over my data table columns and apply glm to each column using a for loop.我正在尝试遍历我的数据表列并使用 for 循环将 glm 应用于每一列。
for(n in 1:ncol(dt)){
model = glm(y ~ dt[, n], family=binomial(link="logit"))
}
Why doesn't this work?为什么这不起作用? I am getting this error:
我收到此错误:
Error in `[.data.table`(dt, , n) :
j (the 2nd argument inside [...]) is a single symbol but column name 'n' is not found. Perhaps you intended DT[, ..n]. This difference to data.frame is deliberate and explained in FAQ 1.1.
I nearly managed to make it work using something like dt[[n]]
, but I think it gets rid of the column name.我几乎设法使用
dt[[n]]
之类的东西使它工作,但我认为它摆脱了列名。
Using lapply
to iterate over columns and reformulate
to construct the formula.使用
lapply
遍历列并reformulate
公式来构造公式。
model_list <- lapply(names(dt), function(x)
glm(reformulate(x, 'y'), dt, family=binomial(link="logit")))
We can create a formula with paste
and use that in glm
我们可以用
paste
创建一个公式并在glm
中使用它
model <- vector('list', ncol(dt))
for(n in 1:ncol(dt)){
model[[n]] = glm(as.formula(paste0('y ~ ', names(dt)[n])),
data = dt, family=binomial(link="logit"))
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.