【问题标题】:How to call regression model by variable in R如何通过R中的变量调用回归模型
【发布时间】:2015-04-13 13:51:13
【问题描述】:

我正在尝试使用 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 

在终端中

contrasts&lt;-(*tmp*, value = contr.funs[1 + isOF[nn]]) 中的错误:

对比只能应用于具有 2 个或更多水平的因素

调用:lm ... model.matrix -> model.matrix.default -> contrasts

另外:警告信息:

在 model.response(mf, "numeric") 中:强制引入的 NAs

执行停止

那么如何使用变量在回归中指定因变量和独立变量?

【问题讨论】:

    标签: r


    【解决方案1】:

    这可能是一个 hacky 解决方案,但您可以将 as.formulapaste 结合使用以使其工作:

    for (dep in var_dep){
        for (indep in var_indep){
            f <- as.formula(paste0(dep, " ~ ", indep))
            lm1 <- lm(f, data = mydata)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-26
      • 2020-07-16
      • 1970-01-01
      • 2021-09-25
      • 1970-01-01
      • 2014-03-28
      相关资源
      最近更新 更多