[英]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.