将 LM 统计信息提取到 table
Extraction LM stats into table
我制作了一个图表,在左上角使用 stat_poly_eq
.
显示线性回归的 r2
、p-value
和 equation
现在我希望将线性回归的统计数据提取到 table。
例如,在 mtcars
数据集中,如果我想对每个 cyl
下一组(例如4, 6, 8) 然后将线性回归统计数据提取到 table,我该怎么做?
谢谢!
这是我的图表:
library(ggplot2)
library(ggpmisc)
formula <- y~x
ggplot(mtcars, aes(disp, hp)) +
geom_point() +
geom_smooth(method = "lm",formula = formula) +
theme_bw()+
facet_wrap(~cyl, scales = "free")+
stat_poly_eq(
aes(label = paste(stat(adj.rr.label), stat(eq.label), stat(p.value.label), sep = "*\", \"*")),
formula = formula, parse = TRUE, size=3)
你的意思是这样的吗?
- 在
nest_by
的情况下,将剩余的列除以每个 cyl
- 用
summarise
,计算每个lm
。您需要将其设置为列表。
- 像使用
map
的普通列表一样操作并计算您需要的东西:系数(可使用 broom::tidy
提取)和 adj.r.squared(使用 summary(.)$adj.r.squared
)
unnest
broom::tidy
的结果来制作一个独特的小标题。
library(dplyr)
library(tidyr)
library(purrr)
mtcars %>%
nest_by(cyl) %>%
summarise(mdl = list(lm(hp ~ disp, data)), .groups = "drop") %>%
mutate(adjrsquared = map_dbl(mdl, ~summary(.)$adj.r.squared ),
mdl = map(mdl, broom::tidy)) %>%
unnest(mdl)
#> # A tibble: 6 x 7
#> cyl term estimate std.error statistic p.value adjrsquared
#> <dbl> <chr> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 4 (Intercept) 47.0 25.3 1.86 0.0960 0.0988
#> 2 4 disp 0.339 0.234 1.45 0.182 0.0988
#> 3 6 (Intercept) 177. 42.0 4.22 0.00829 0.117
#> 4 6 disp -0.300 0.224 -1.34 0.238 0.117
#> 5 8 (Intercept) 178. 77.4 2.30 0.0405 -0.0682
#> 6 8 disp 0.0890 0.216 0.413 0.687 -0.0682
我制作了一个图表,在左上角使用 stat_poly_eq
.
r2
、p-value
和 equation
现在我希望将线性回归的统计数据提取到 table。
例如,在 mtcars
数据集中,如果我想对每个 cyl
下一组(例如4, 6, 8) 然后将线性回归统计数据提取到 table,我该怎么做?
谢谢!
这是我的图表:
library(ggplot2)
library(ggpmisc)
formula <- y~x
ggplot(mtcars, aes(disp, hp)) +
geom_point() +
geom_smooth(method = "lm",formula = formula) +
theme_bw()+
facet_wrap(~cyl, scales = "free")+
stat_poly_eq(
aes(label = paste(stat(adj.rr.label), stat(eq.label), stat(p.value.label), sep = "*\", \"*")),
formula = formula, parse = TRUE, size=3)
你的意思是这样的吗?
- 在
nest_by
的情况下,将剩余的列除以每个cyl
- 用
summarise
,计算每个lm
。您需要将其设置为列表。 - 像使用
map
的普通列表一样操作并计算您需要的东西:系数(可使用broom::tidy
提取)和 adj.r.squared(使用summary(.)$adj.r.squared
) unnest
broom::tidy
的结果来制作一个独特的小标题。
library(dplyr)
library(tidyr)
library(purrr)
mtcars %>%
nest_by(cyl) %>%
summarise(mdl = list(lm(hp ~ disp, data)), .groups = "drop") %>%
mutate(adjrsquared = map_dbl(mdl, ~summary(.)$adj.r.squared ),
mdl = map(mdl, broom::tidy)) %>%
unnest(mdl)
#> # A tibble: 6 x 7
#> cyl term estimate std.error statistic p.value adjrsquared
#> <dbl> <chr> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 4 (Intercept) 47.0 25.3 1.86 0.0960 0.0988
#> 2 4 disp 0.339 0.234 1.45 0.182 0.0988
#> 3 6 (Intercept) 177. 42.0 4.22 0.00829 0.117
#> 4 6 disp -0.300 0.224 -1.34 0.238 0.117
#> 5 8 (Intercept) 178. 77.4 2.30 0.0405 -0.0682
#> 6 8 disp 0.0890 0.216 0.413 0.687 -0.0682