R 将LM stats提取到表中
我用R 将LM stats提取到表中,r,tidyverse,linear-regression,R,Tidyverse,Linear Regression,我用stat\u poly\u eq在左上角的线性回归图中绘制了一个显示r2、p值和方程的图表 现在,我希望将线性回归的统计数据提取到一个表中 例如,在mtcars数据集中,如果我想对每个cylinder组(例如4、6、8)的hp曲线图与disp进行线性回归,然后将线性回归统计数据提取到表中,我该怎么做 谢谢 这是我的图表: library(ggplot2) library(ggpmisc) formula <- y~x ggplot(mtcars, aes(disp, hp)) +
stat\u poly\u eq
在左上角的线性回归图中绘制了一个显示r2
、p值
和方程的图表
现在,我希望将线性回归的统计数据提取到一个表中
例如,在mtcars
数据集中,如果我想对每个cyl
inder组(例如4、6、8)的hp
曲线图与disp
进行线性回归,然后将线性回归统计数据提取到表中,我该怎么做
谢谢
这是我的图表:
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)
库(ggplot2)
图书馆(ggpmisc)
你的意思是这样的吗
- 使用
nest_by
,将分开的tible中的其余列除以每个cyl
- 使用
summary
,计算每个lm
。您需要将其设置为一个列表
- 使用
map
像普通列表一样操作,并计算您需要的内容:系数(可使用broom::tidy
提取)和adj.r.squared(使用摘要(.)$adj.r.squared
)
unnest
扫帚::整理的结果
以生成唯一的TIBLE
库(dplyr)
图书馆(tidyr)
图书馆(purrr)
mtcars%>%
嵌套单位(循环)%>%
总结(mdl=列表(lm(hp~disp,数据)),.groups=“drop”)%>%
变异(adjrsquared=map_dbl(mdl,~summary(.)$adj.r.squared),
mdl=map(mdl,扫帚::整齐))%>%
unnest(mdl)
#>#tibble:6 x 7
#>气缸项估计标准误差统计p值调整平方
#>
#>1 4(截距)47.0 25.3 1.86 0.0960 0.0988
#>2 4显示0.339 0.234 1.45 0.182 0.0988
#>36(拦截)177。42.0 4.22 0.00829 0.117
#>4 6 disp-0.300 0.224-1.34 0.238 0.117
#>5 8(拦截)178。77.4 2.30 0.0405 -0.0682
#>6 8 disp 0.0890 0.216 0.413 0.687-0.0682
你的意思是这样的吗
- 使用
nest_by
,将分开的tible中的其余列除以每个cyl
- 使用
summary
,计算每个lm
。您需要将其设置为一个列表
- 使用
map
像普通列表一样操作,并计算您需要的内容:系数(可使用broom::tidy
提取)和adj.r.squared(使用摘要(.)$adj.r.squared
)
unnest
扫帚::整理的结果
以生成唯一的TIBLE
库(dplyr)
图书馆(tidyr)
图书馆(purrr)
mtcars%>%
嵌套单位(循环)%>%
总结(mdl=列表(lm(hp~disp,数据)),.groups=“drop”)%>%
变异(adjrsquared=map_dbl(mdl,~summary(.)$adj.r.squared),
mdl=map(mdl,扫帚::整齐))%>%
unnest(mdl)
#>#tibble:6 x 7
#>气缸项估计标准误差统计p值调整平方
#>
#>1 4(截距)47.0 25.3 1.86 0.0960 0.0988
#>2 4显示0.339 0.234 1.45 0.182 0.0988
#>36(拦截)177。42.0 4.22 0.00829 0.117
#>4 6 disp-0.300 0.224-1.34 0.238 0.117
#>5 8(拦截)178。77.4 2.30 0.0405 -0.0682
#>6 8 disp 0.0890 0.216 0.413 0.687-0.0682
我添加了adj.r.squared
我添加了adj.r.squared
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