r - 循环遍历数据表列并应用 glm
问题描述
我正在尝试遍历我的数据表列并glm
使用 for 循环应用于每一列。然后我想从模型中提取回归系数并将它们添加到我的输出数据表中。
这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.
解决方案
您可以应用模型并在同一循环中提取系数。使用lapply
:
output <- do.call(rbind, lapply(names(dt), function(x) {
model <- glm(reformulate(x, 'y'), dt, family=binomial(link="logit"))
summary(model)$coefficients[2]
}))
推荐阅读
- typescript - 如何跳过在 inter 4 中使用 tdd 接口创建的测试?
- r - 使用 meffil 进行 Illumina EPIC 甲基化分析
- command - 如何在 git 中提交特定的更改
- python - 解析格式为 20120101 1:00 的数据
- angular - 在主题订阅方法中调用时,Angular 5 ng-bootstrap 模态未正确显示
- matlab - 如何在 MATLAB 中合并两个函数?
- c++ - Qt5,在行中设置文字大小编辑
- docker - Docksal:如何启用 HTTPS / SSL?
- ruby-on-rails - 结合两个 each_with_object 迭代器
- sql-server - SQL Server:CASE 中的“=”语法错误