从 R 中的线性模型回归了解输出系数

时间:2021-02-23 13:38:02

标签: r lm anova coefficients interpretation

我目前正在阅读一本相当简单的假设教科书。被解释为线性模型的系数,其中自变量是两个分别具有 2 个和 3 个因子的分类变量,而因变量是一个连续变量,应解释为;因变量的总体均值(所有分类变量和因子的均值)与因变量的均值之间的差异(基于给定分解分类变量的因变量值)。我希望这是可以理解的。

然而,当我试图重现书中的例子时,我没有得到相同的系数,std。错误,T 值或 P 值。

我使用 ToothGrowth 数据集创建了一个可重现的示例,情况也是如此:

library(tidyverse)

# Transforming Data to a Tibble and Change Variable 'dose' to a Factor:
tooth_growth_reprex <- ToothGrowth %>%
  as_tibble() %>%
  mutate(dose = as.factor(dose))

# Creating Linear Model of Variables in ToothGrowth (tg):
tg_lm <- lm(formula = len ~ supp * dose, data = tooth_growth_reprex)

# Extracting suppVC coefficient:
(coef_supp_vc <- tg_lm$coefficients["suppVC"])
#> suppVC 
#>  -5.25

# Calculating Mean Difference between Overall Mean and Supplement VC Mean:
## Overall Mean:
(overall_summary <- tooth_growth_reprex %>%
  summarise(Mean = mean(len)))
#> # A tibble: 1 x 1
#>    Mean
#>   <dbl>
#> 1  18.8

## Supp VC Mean:
(supp_vc_summary <- tooth_growth_reprex %>%
  group_by(supp) %>%
  summarise(Mean = mean(len))) %>% 
  filter(supp == "VC")
#> # A tibble: 1 x 2
#>   supp   Mean
#>   <fct> <dbl>
#> 1 VC     17.0

## Difference between Overall Mean and Supp VC Mean:
(mean_dif_overall_vc <- overall_summary$Mean - supp_vc_summary$Mean[2])
#> [1] 1.85

# Testing if supp_VC coefficient and difference between Overall Mean and Supp VC Mean is near identical:
near(coef_supp_vc, mean_dif_overall_vc)
#> suppVC 
#>  FALSE

reprex package (v1.0.0) 于 2021 年 2 月 23 日创建

我的问题:

  1. 我对系数值的理解是否完全错误?
  2. lm 实际计算的系数是多少?
  3. R 中是否有任何函数可以计算我感兴趣的内容,而我必须手动完成?

我希望这是足够的信息。如果没有,请不要犹豫,问我!

1 个答案:

答案 0 :(得分:0)

lm() 函数使用虚拟编码,因此模型中的所有系数都与参考组的平均值进行比较。这里的参考组是你的因子的第一级,所以 supp=OJdose=0.5

然后您可以像这样进行验证:

coef(tg_lm)["(Intercept)"] + coef(tg_lm)["suppVC"] == mean_table %>% filter(supp=='VC' & dose==0.5) %>% pull(M)

(coef(tg_lm)["(Intercept)"] + coef(tg_lm)["suppVC"] + coef(tg_lm)["dose1"] + coef(tg_lm)["suppVC:dose1"]) == mean_table %>% filter(supp=='VC' & dose==1) %>% pull(M)

您可以阅读差异here