【问题标题】:Understanding the Output Coefficients from a Linear Model Regression in R了解 R 中线性模型回归的输出系数
【发布时间】:2021-05-25 18:55:15
【问题描述】:

我目前正在阅读一本相当简单的假设教科书。正在解释的是来自线性模型的系数,其中自变量是两个分类变量,分别具有 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 中是否有任何函数可以计算我感兴趣的内容,而我必须手动计算?

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

【问题讨论】:

    标签: r lm anova coefficients interpretation


    【解决方案1】:

    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

    【讨论】:

    • 非常感谢您为我指引正确的方向@erocoar!我已经阅读了您所链接的内容,并且我了解到在这种情况下,虚拟编码确实不是我想要的回归模型。但是,我似乎无法弄清楚如何通过虚拟编码以外的任何其他方式来改变 lm 函数对分类变量和因子建模的方式。我最好的猜测是,它与 lm 函数的“对比”参数有关,但我几乎处于赤裸状态。你有什么主意吗?如果我找到解决问题的方法,我会继续挖掘并发布。
    • 我在stats.stackexchange.com/questions/52132/…找到了解决办法contr.SAS、contr.sum、contr.treatment、contr.poly 或 contr.helmert。不同的对比提供了不同类型的分类变量编码,在我的情况下,想要将每个分类变量的每个因子的因变量的平均值与总平均值进行比较, contr.sum 做到了。再次,非常感谢您让我朝着正确的方向前进!
    • 很高兴听到您找到了解决方案 :) 我自己也不知道对比论点。
    猜你喜欢
    • 2020-01-17
    • 2018-04-28
    • 2020-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多