You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

自动化回归函数报错求助:R语言多因变量线性回归构建问题

批量线性回归代码修正与解决方案

问题背景

现有变量列表与分组变量:

elscincarticles <- c("total_info_inst_org_plan", "total_info_relev_jurid", "total_info_eco_pres_est", "total_art_portal", "total_onze")
group_var <- c("Tramspoblacio")

目标是对elscincarticles中每个元素作为因变量,以group_var为自变量执行线性回归,原代码运行报错:

regression <- data_frame(
  formula = elscincarticles, paste('~ "Tramspoblacio'), 
  model = map(
    .x = formula, 
    .f = function(x) lm(x, data = index_articles))
)

报错信息:

Error in `map()`:
i In index: 1.
Caused by error in `formula.character()`:
! invalid formula "total_info_inst_org_plan": not a call
Backtrace:
  1. tibble::data_frame(...)
  5. purrr::map(.x = formula, .f = function(x) lm(x, data = index_articles))
  6. purrr:::map_("list", .x, .f, ..., .progress = .progress)
 10. .f(.x[[i]], ...)
 15. stats::model.frame.default(...)
 16. stats::as.formula(formula)
 18. stats:::formula.character(object, env = baseenv())
 19. base::stop(...)

错误原因

  1. 公式拼接错误:原代码未将因变量与自变量拼接成合法的公式字符串,formula列仅存储了因变量名称,lm()无法识别单独的变量名为有效公式。
  2. data_frame语法错误:列定义方式不正确,未正确生成完整公式列。

修正代码

使用paste()生成完整的公式字符串,再通过purrr::map()批量拟合模型:

library(tibble)
library(purrr)
library(stargazer)

# 生成完整的公式向量
formulas <- paste(elscincarticles, "~", group_var)

# 批量拟合模型并存储为tibble
regression <- tibble(
  outcome_var = elscincarticles,
  formula = formulas,
  model = map(formulas, ~ lm(as.formula(.x), data = index_articles))
)

结果输出

直接调用stargazer()输出所有模型结果:

stargazer(regression$model, type = 'text')

内容的提问来源于stack exchange,提问作者FrancoBattiato

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 11:02:20