我目前正在阅读一本相当简单的假设教科书。被解释为线性模型的系数,其中自变量是两个分别具有 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 日创建
我的问题:
我希望这是足够的信息。如果没有,请不要犹豫,问我!
答案 0 :(得分:0)
lm()
函数使用虚拟编码,因此模型中的所有系数都与参考组的平均值进行比较。这里的参考组是你的因子的第一级,所以 supp=OJ
和 dose=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