【问题标题】:Loop over data table columns and apply glm循环遍历数据表列并应用 glm
【发布时间】:2021-03-30 10:13:29
【问题描述】:

我正在尝试遍历我的数据表列,并使用 for 循环将 glm 应用于每一列。然后我想从模型中提取回归系数并将它们添加到我的输出数据表中。

这里dt是一个数据表,y是一个向量:

output = data.table('reg_coef' = numeric())
for(n in 1:ncol(dt)){
  model = glm(y ~ dt[, n], family=binomial(link="logit"))
  reg_coef = summary(model)$coefficients[2]
  output = rbindlist(list(output, list(reg_coef)))
}

为什么这不起作用?我收到此错误:

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. 

【问题讨论】:

    标签: r for-loop datatable


    【解决方案1】:

    您可以在同一循环中应用模型并提取系数。使用lapply

    output <- do.call(rbind, lapply(names(dt), function(x) {
      model <- glm(reformulate(x, 'y'), dt, family=binomial(link="logit"))
      summary(model)$coefficients[2]
    }))
    

    【讨论】:

    • 如果我必须提取多个系数怎么办?
    • 感谢您提供更新的答案,是 rbind 还是 rbindlist 更好?我看到一个帖子说rbind的性能更差。
    • 您的数据中有多少列?
    • @Ronak_Shah ~100
    【解决方案2】:

    我们可以使用paste

    output <- do.call(rbind, lapply(names(dt), function(x) {
     model <- glm(as.formula(paste0('y ~ ', x)), dt, family=binomial(link="logit"))
      summary(model)$coefficients[2]
       }))
    

    【讨论】:

      猜你喜欢
      • 2021-06-26
      • 1970-01-01
      • 2017-11-06
      • 2012-08-25
      • 2012-05-30
      • 1970-01-01
      • 2018-05-30
      • 2017-10-27
      相关资源
      最近更新 更多