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

如何向dplyr::group_map()的输出结果中添加group_by分组键变量

解决方案

有几种简便的实现方式:

方法1:用group_modify替换group_map(最便捷)

group_modify是dplyr专门针对分组数据做修改的函数,会自动保留分组键到最终输出结果中,代码修改如下:

iris %>% 
  group_by(Species) %>% 
  group_modify(~ broom::tidy(lm(Sepal.Length ~ Sepal.Width, data = .x))) %>% 
  ungroup()

方法2:在group_map中调用分组键参数.y

如果需要保留group_map的写法,可以利用group_map回调函数的第二个默认参数.y,它本身就是当前分组的分组键tibble,直接和回归结果绑定即可:

iris %>% 
  group_by(Species) %>% 
  group_map(~ bind_cols(.y, broom::tidy(lm(Sepal.Length ~ Sepal.Width, data = .x)))) %>% 
  bind_rows()

方法3:用nest_by + unnest的写法

这种写法逻辑更清晰,适合更复杂的多模型批量计算场景:

iris %>% 
  nest_by(Species) %>% 
  mutate(model_res = list(broom::tidy(lm(Sepal.Length ~ Sepal.Width, data = data)))) %>% 
  unnest(model_res) %>% 
  select(-data)

以上三种方法输出的结果都会自带Species分组列,效果如下:

# A tibble: 6 × 6
  Species    term        estimate std.error statistic  p.value
  <fct>      <chr>          <dbl>     <dbl>     <dbl>    <dbl>
1 setosa     (Intercept)    2.64     0.310       8.51 3.74e-11
2 setosa     Sepal.Width    0.690    0.0899      7.68 6.71e-10
3 versicolor (Intercept)    3.54     0.563       6.29 9.07e- 8
4 versicolor Sepal.Width    0.865    0.202       4.28 8.77e- 5
5 virginica  (Intercept)    3.91     0.757       5.16 4.66e- 6
6 virginica  Sepal.Width    0.902    0.253       3.56 8.43e- 4

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 14:30:02