R语言broom包整洁化模型
broom是tidyverse系列包之一,可以帮助人们获得干净整洁的模型数据结果,有效改善了R语言建模的用户体验
载入包
library(tidyverse)
#broom包需要另行载入
library(broom)
建模
#使用mtcars数据集
fit <- lm(mpg~disp,data = mtcars)
fit
Call:
lm(formula = mpg ~ disp, data = mtcars)
Coefficients:
(Intercept) disp
29.59985 -0.04122
summary(fit)
#lm返回列表结果,内涵各种数据,在平时应用中不方便整理使用
broom:整洁模型数据
broom可以使建模结果变量更加整洁,主要有三个常用函数
-
augment
:查看构成模型的每个样本的情况 -
glance
:查看模型总体情况 -
tidy
:查看模型截距、估计等
#用于控制小数点的函数
easyround <- function(x,digits = 3) {
res <- map_if(x,is.numeric,round,digits) %>% as_tibble()
return(res)
}
augment(fit) %>%
head() %>%
easyround()
# A tibble: 6 x 9
.rownames mpg disp .fitted .resid .std.resid .hat .sigma .cooksd
<chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 Mazda RX4 21 160 23.0 -2.00 -0.63 0.042 3.28 0.009
2 Mazda RX4 Wag 21 160 23.0 -2.00 -0.63 0.042 3.28 0.009
3 Datsun 710 22.8 108 25.1 -2.35 -0.746 0.063 3.28 0.019
4 Hornet 4 Drive 21.4 258 19.0 2.43 0.761 0.033 3.28 0.01
5 Hornet Sportabout 18.7 360 14.8 3.94 1.25 0.066 3.22 0.056
6 Valiant 18.1 225 20.3 -2.23 -0.696 0.031 3.28 0.008
glance(fit)[,1:5] %>%
easyround()
# A tibble: 1 x 5
r.squared adj.r.squared sigma statistic p.value
<dbl> <dbl> <dbl> <dbl> <dbl>
1 0.718 0.709 3.25 76.5 0
tidy(fit) %>% easyround()
# A tibble: 2 x 5
term estimate std.error statistic p.value
<chr> <dbl> <dbl> <dbl> <dbl>
1 (Intercept) 29.6 1.23 24.1 0
2 disp -0.041 0.005 -8.75 0
purrr包向量化函数与broom包结合
purrr包向量化函数与broom包配合使用可以极大简化数据分析复杂程度,优化时间。
#使用了split函数将数据集按照分类变量取值分组
mtcars %>%
split(.$cyl) %>%
map(.,~lm(mpg~disp,data =. )) %>%
map(.,tidy) %>%
map(.,easyround)
$`4`
# A tibble: 2 x 5
term estimate std.error statistic p.value
<chr> <dbl> <dbl> <dbl> <dbl>
1 (Intercept) 40.9 3.59 11.4 0
2 disp -0.135 0.033 -4.07 0.003
$`6`
# A tibble: 2 x 5
term estimate std.error statistic p.value
<chr> <dbl> <dbl> <dbl> <dbl>
1 (Intercept) 19.1 2.91 6.55 0.001
2 disp 0.004 0.016 0.232 0.826
$`8`
# A tibble: 2 x 5
term estimate std.error statistic p.value
<chr> <dbl> <dbl> <dbl> <dbl>
1 (Intercept) 22.0 3.34 6.59 0
2 disp -0.02 0.009 -2.11 0.057
# 再结合bind_rows函数可以把三个模型数据框合并
mtcars %>%
split(.$cyl) %>%
map(.,~lm(mpg~disp,data =. )) %>%
map(.,tidy) %>%
bind_rows() %>%
easyround()
# A tibble: 6 x 5
term estimate std.error statistic p.value
<chr> <dbl> <dbl> <dbl> <dbl>
1 (Intercept) 40.9 3.59 11.4 0
2 disp -0.135 0.033 -4.07 0.003
3 (Intercept) 19.1 2.91 6.55 0.001
4 disp 0.004 0.016 0.232 0.826
5 (Intercept) 22.0 3.34 6.59 0
6 disp -0.02 0.009 -2.11 0.057
也可以结合tidyverse包获得更tidy的结果
#summarise函数也可以换成mutate函数
mtcars %>%
group_by(cyl) %>%
nest() %>%
mutate(fit = map(data,~lm(mpg~disp,data = .))) %>%
summarise(tidyfit = map(fit,~tidy(.))) %>%
unnest(tidyfit) %>%
easyround()
# A tibble: 6 x 6
cyl term estimate std.error statistic p.value
<dbl> <chr> <dbl> <dbl> <dbl> <dbl>
1 4 (Intercept) 40.9 3.59 11.4 0
2 4 disp -0.135 0.033 -4.07 0.003
3 6 (Intercept) 19.1 2.91 6.55 0.001
4 6 disp 0.004 0.016 0.232 0.826
5 8 (Intercept) 22.0 3.34 6.59 0
6 8 disp -0.02 0.009 -2.11 0.057