r - 如何将关键变量添加到 `dplyr::group_map()` ?

标签 r dplyr split-apply-combine

我有以下内容,但想添加 group_by() key Species到由此产生的小标题:
移动电源

iris %>% 
  group_by(Species) %>% 
  group_map(~ broom::tidy(lm(Sepal.Length ~ Sepal.Width, data = .x))) %>% 
  bind_rows()
输出
# How do I add the grouping key `Species` to this?

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

最佳答案

您可以使用 group_modify()而不是 group_map() .

library(purrr)
library(dplyr)

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

# A tibble: 6 x 6
# Groups:   Species [3]
  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

关于r - 如何将关键变量添加到 `dplyr::group_map()` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69068063/

相关文章:

python - 具有宽/长旋转的 Groupby 累积平均值

r - 按列分组,然后计算 R 中每隔一列的均值和标准差

r - R中的函数 "else"

r - 绘制 geom_point 和 geom_line

r - dplyr::mutate new columns based on a second (filtered) dataframe

r - 在 R 中创建唯一 ID 列

r - 在 R data.table 中粘贴多列对的有效方法

r - 内插空间数据

r - Sweave编译完成后如何删除aux/log/out

r - 确定函数返回值是否为 dplyr 对象