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

如何将R中多组线性模型的系数从tibble导出至CSV?

解决方案

要从存储在tibble中的分组线性模型里提取系数并导出为CSV,你可以借助broom包(专门用于整理模型输出)或者purrr工具批量处理每个模型对象,以下是两种可行方法:

方法1:使用broom包(推荐,输出完整统计信息)

broom::tidy()能将单个模型的系数、标准误、p值等信息整理成结构化表格,结合dplyr和tidyr可批量处理所有分组模型:

# 先安装并加载所需包
install.packages("broom")
library(broom)
library(dplyr)
library(tidyr)

# 提取每个月份模型的完整系数统计信息
model_coefficients <- MMF_reggression %>%
  # 对每个lm模型应用tidy,生成系数表
  mutate(coef_details = map(model, tidy)) %>%
  # 将嵌套的系数表展开为常规行
  unnest(coef_details) %>%
  # 保留需要的列(可根据需求调整)
  select(Month, term, estimate, std.error, statistic, p.value)

# 导出到CSV文件
write.csv(model_coefficients, file = "regionalregression.csv", row.names = FALSE)

方法2:手动提取核心系数(仅截距和斜率)

如果只需要截距和斜率这两个核心系数,可用purrr::map_dbl()逐个提取:

library(purrr)
library(dplyr)

# 提取每个模型的截距和斜率
model_coefficients <- MMF_reggression %>%
  mutate(
    intercept = map_dbl(model, ~ coef(.)["(Intercept)"]),
    slope = map_dbl(model, ~ coef(.)["DRAINAGE_AREA_GROSS"])
  ) %>%
  select(Month, intercept, slope)

# 导出CSV
write.csv(model_coefficients, file = "regionalregression.csv", row.names = FALSE)

问题说明

你之前尝试的coef(MMF_reggression[[,2]])无效,是因为tibble的model列是列表列,每个元素是独立的lm模型对象,coef()无法直接作用于整个列表,必须逐个处理每个模型的系数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 14:02:35