【问题标题】:How to retrieve slopes and standard errors of the slopes of two simple linear regression lines?如何检索两条简单线性回归线的斜率和标准误?
【发布时间】:2021-08-02 07:43:09
【问题描述】:

我有这个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))

如何获取这四个变量:

斜率来自 A 组的简单线性回归线(比较 x 和 y)。

斜率来自 B 组的简单线性回归线(比较 x 和 y)。

斜率的标准误差来自 A 组的简单线性回归线(比较 x 和 y)。

斜率的标准误差来自 B 组的简单线性回归线(比较 x 和 y)。

【问题讨论】:

  • 您尝试过哪些不起作用的方法?

标签: r linear-regression standard-error


【解决方案1】:

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

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  

【讨论】:

  • 非常好!谢谢。
  • 斜率的标准误是0.228和0.125吗?
  • 它是系数的标准误差。它测量系数估计值与响应变量的实际平均值不同的平均量。如果您想比较拟合的优劣,请改为检查 R 平方。将tidy 更改为glance
  • 我还有一个问题。我怎样才能抓住价值?例如,如果我希望 A.se 为 0.228,B.se 为 0.125?像df2 &lt;- df %&gt;% split(.$p) %&gt;% map(~lm(y~x, data = .) %&gt;% broom::tidy(.)) 然后A.se &lt;- unlist(temp["0"],use.names=T)[2]?还是有更简单的方法?
  • @SylviaRodriguez 试试map_dbl(~slice(., 2) %&gt;% pull(std.error))
【解决方案2】:
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)

这四个问题的答案在回归摘要的系数选项卡中给出(其中“估计”是斜率,“标准误差”是斜率的标准误差)。

【讨论】:

  • 谢谢。线性模型(lm)和简单的线性回归一样吗?
  • 你是对的。在 Rstudio 的帮助部分输入 lm 将提供更多详细信息
  • 另请注意,您的陈述“比较 x 与 y”并没有告诉您哪个变量是自变量,哪个变量是因变量(被预测)。对于这个例子,我假设 y 被用来预测 x,如果是另一种方式,那么将公式翻转到 y~x
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-25
  • 1970-01-01
  • 1970-01-01
  • 2020-05-05
  • 1970-01-01
  • 1970-01-01
  • 2016-06-07
相关资源
最近更新 更多