r - 如何在R中通过变量调用回归模型

标签 r

我正在尝试使用 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.formulapaste 结合使用来使其发挥作用:

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/

相关文章:

r - 如何修复 tm 包以奇怪的顺序加载大量文档的问题?

r - ggplot2:更改置信区域的颜色以匹配线条的颜色

r - 您如何处理包内部的 R 数据?

r - 在 AWS EC2 上使用 doRedis 和 doMC 在 R 中进行多核/并行模拟

r - 在 `paste` 函数中使用未定义(拼写错误)的参数 - 了解结果

R - 如何从日期列中选择最早的日期列?

R Markdown : Can't access Bash command installed through Conda/Anaconda

r - 包安装需要较新版本的依赖项

r - 如何重置几个actionButtons的值? ( Shiny 包)

r - 考虑到数据的子集,如何获得每个数据帧行的百分位值?