使用扫帚的整洁功能
library(purrr)
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
library(tidyr)
library(broom)
cyl_group<-mtcars %>% group_by(cyl) %>%
nest()
cyl_lm<-cyl_group %>% mutate(
mod=map(data,~lm(mpg ~ wt, data = .x))
) %>% mutate(coef=map(mod,~tidy(.x))) %>% unnest(coef)
cyl_lm
#> # A tibble: 6 x 8
#> # Groups: cyl [3]
#> cyl data mod term estimate std.error statistic p.value
#> <dbl> <list> <list> <chr> <dbl> <dbl> <dbl> <dbl>
#> 1 6 <tibble [7 x 10~ <lm> (Interce~ 28.4 4.18 6.79 1.05e-3
#> 2 6 <tibble [7 x 10~ <lm> wt -2.78 1.33 -2.08 9.18e-2
#> 3 4 <tibble [11 x 1~ <lm> (Interce~ 39.6 4.35 9.10 7.77e-6
#> 4 4 <tibble [11 x 1~ <lm> wt -5.65 1.85 -3.05 1.37e-2
#> 5 8 <tibble [14 x 1~ <lm> (Interce~ 23.9 3.01 7.94 4.05e-6
#> 6 8 <tibble [14 x 1~ <lm> wt -2.19 0.739 -2.97 1.18e-2
由reprex 包(v0.3.0)于 2020 年 8 月 19 日创建