如何检索两条简单线性回归线斜率的斜率和标准误差?

How to retrieve slopes and standard errors of the slopes of two simple linear regression lines?

我有这个data.frame:

 set.seed(12345)
 df <- data.frame(
      p=c(rep("A", 39), rep("B",61)),
      x=rnorm(100, 34, 20), 
      y=rnorm(100, 21, 25))

如何获取这四个变量:

Slope from simple linear regression line from group A (comparing x to y).

Slope from simple linear regression line from group B (comparing x to y).

Standard error of the slope from simple linear regression line from group A (comparing x to y).

Standard error of the slope from simple linear regression line from group B (comparing x to y).

library(tidyverse)

set.seed(12345)
df <- data.frame(
  p=c(rep("A", 39), rep("B",61)),
  x=rnorm(100, 34, 20), 
  y=rnorm(100, 21, 25))


#fit the regression
lm_A = lm(x~y, data=df %>% filter(p == "A"))
summary(lm_A)

lm_B = lm(x~y, data=df %>% filter(p == "B"))
summary(lm_B)

这四个问题的答案在回归摘要的系数选项卡中给出(其中 'Estimate' 是斜率,'Std. Error' 是斜率的标准误差)。

数以千计的可能性。 你可以试试这个可视化:

library(tidyverse)
library(ggpubr)
df %>%
  filter(p == "A") %>% 
  ggplot(aes(x, y, color = p)) + 
   geom_point() + 
   geom_smooth(method = "lm") + 
   ggpubr::stat_regline_equation(show.legend = F) 
   geom_abline(slope = 0.0269, intercept = 38.3)

这是值:

library(broom)
df %>% 
  split(.$p) %>% 
  map(~lm(y~x, data = .) %>% broom::tidy(.))
$A
# A tibble: 2 x 5
  term        estimate std.error statistic p.value
  <chr>          <dbl>     <dbl>     <dbl>   <dbl>
1 (Intercept)  21.2       10.1       2.11   0.0420
2 x             0.0517     0.228     0.227  0.822 

$B
# A tibble: 2 x 5
  term        estimate std.error statistic p.value
  <chr>          <dbl>     <dbl>     <dbl>   <dbl>
1 (Intercept)   15.5       5.67       2.74 0.00821
2 x              0.153     0.125      1.22 0.229