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

如何从嵌套列表中提取R语言分组线性模型的系数?

高效将分组线性模型系数转为数据框的方法

方案1:用dplyr + broom一步到位(推荐,无需手动处理嵌套列表)

直接从原始数据出发,通过分组建模并自动整理系数,完全避开手动拆分列表的繁琐:

library(dplyr)
library(broom)

# 从原始数据直接生成目标数据框
wanted <- d %>%
  group_by(class) %>%
  do(tidy(lm(y ~ x, data = .))) %>%  # 对每个分组建模并整理系数为整洁格式
  pivot_wider(names_from = term, values_from = estimate) %>%  # 将行转列,分开截距和斜率
  rename(intercept = `(Intercept)`, slope = x) %>%  # 重命名列
  select(class, slope, intercept)  # 调整列顺序

方案2:处理已生成的m.s列表(base R版本)

如果已经得到了m.s列表,用base R也可以快速转为数据框:

# 将列表转为矩阵再转数据框
coeff_matrix <- do.call(rbind, m.s)
wanted <- as.data.frame(coeff_matrix)
# 添加class列(利用列表的名称)
wanted$class <- rownames(wanted)
# 重命名并调整列顺序
wanted <- wanted[, c("class", "x", "(Intercept)")]
names(wanted) <- c("class", "slope", "intercept")

方案3:处理已生成的m.s列表(purrr版本)

用purrr的函数更简洁地拆分嵌套列表:

library(purrr)
library(tibble)

wanted <- tibble(class = names(m.s), coeffs = m.s) %>%
  unnest_wider(coeffs) %>%  # 展开嵌套的系数列表
  rename(intercept = `(Intercept)`, slope = x) %>%
  select(class, slope, intercept)

以上方法都比手动unlist再拆分行名高效得多,尤其是方案1,从数据到结果全程流式操作,完全不用和嵌套列表打交道,适配你避免繁琐列表操作的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 00:52:34