我正在尝试使用 R 脚本评估一系列单变量回归模型。我的数据采用 .csv 文件格式,其中前 8 列代表我们想要预测的因变量,接下来的 52 列代表可用于拟合 8 个因变量中任何一个的自变量。
我已成功将数据读入脚本。我还为向量中的因变量和自变量创建了一个标题列表。所以我的脚本如下所示:
#... do some stuff to get data above
var_dep<-c("dep1","dep2",...)
var_indep<-c("indep1","indep2",...)
for(dep in var_dep){
for(indep in var_indep){
lm1<-lm(dep~indep, data=mydat)
}
}
运行时收到此错误消息
Rscript R_ScriptV2.R XLK_friendly.csv
在终端
Error in
contrasts<-
(*tmp*
, value = contr.funs[1 + isOF[nn]]) :contrasts can be applied only to factors with 2 or more levels
Calls: lm ... model.matrix -> model.matrix.default -> contrasts<-
In addition: Warning message:
In model.response(mf, "numeric") : NAs introduced by coercion
Execution halted
那么如何使用变量指定回归中的因变量和独立变量?
最佳答案
这可能是一个 hacky 解决方案,但您可以将 as.formula
与 paste
结合使用来使其发挥作用:
for (dep in var_dep){
for (indep in var_indep){
f <- as.formula(paste0(dep, " ~ ", indep))
lm1 <- lm(f, data = mydata)
}
}
关于r - 如何在R中通过变量调用回归模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28484052/