[英]Loop over data table columns and apply glm using for loop
我正在尝试遍历我的数据表列并使用 for 循环将 glm 应用于每一列。
for(n in 1:ncol(dt)){
model = glm(y ~ dt[, n], family=binomial(link="logit"))
}
为什么这不起作用? 我收到此错误:
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.
我几乎设法使用dt[[n]]
之类的东西使它工作,但我认为它摆脱了列名。
使用lapply
遍历列并reformulate
公式来构造公式。
model_list <- lapply(names(dt), function(x)
glm(reformulate(x, 'y'), dt, family=binomial(link="logit")))
我们可以用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.