r - lm 或 coxph 的未知对比度的方差

标签 r regression linear-regression variance coding-efficiency

我正在利用我的question from yesterday

假设我们有三种处理方法,并且想要获得所有成对差异。 R 中的默认设置是使用对比度,并且仅显示 2。即 2 vs 1 和 3 vs 1。为了获得 3 vs 2,我们需要减去 beta 系数(3vs 1 - 2 vs 1)。

现在我们有了估计值,但是有没有办法获得该估计值的方差?或者我们是否必须使用不同的引用组再次运行回归才能得到它?

最佳答案

我们可以使用 multcomp 包中的 glht 函数进行事后测试,并提供针对多个测试进行调整的选项。 (有关更多示例,请参阅 http://www.ats.ucla.edu/stat/r/faq/testing_contrasts.htm)

一个小例子

library(multcomp)
data(mtcars)
mtcars$cyl <- factor(mtcars$cyl, levels=c(4, 6, 8))

# run model
m <- lm(mpg ~ cyl, data=mtcars)
coef(summary(m))
#               Estimate Std. Error   t value     Pr(>|t|)
# (Intercept)  26.663636  0.9718008 27.437347 2.688358e-22
# cyl6         -6.920779  1.5583482 -4.441099 1.194696e-04
# cyl8        -11.563636  1.2986235 -8.904534 8.568209e-10
coef(m)[2] - coef(m)[3]
#     cyl6 
# 4.642857 

# use glht function to estimate other contrasts
# define the linfct matrix to test specific contrast
mf <- glht(m, linfct = matrix(c(0, 1, -1), 1))
summary(mf)
#    Simultaneous Tests for General Linear Hypotheses
# 
# Fit: lm(formula = mpg ~ cyl, data = mtcars)
# 
# Linear Hypotheses:
#        Estimate Std. Error t value Pr(>|t|)   
# 1 == 0    4.643      1.492   3.112  0.00415 **
# ---
# Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
# (Adjusted p values reported -- single-step method)

# look at estimate by changing the reference level manually
mtcars$cyl2 <- factor(mtcars$cyl, levels=c(6, 4, 8))
m2 <- lm(mpg ~ cyl2, data=mtcars)
coef(summary(m2))
#              Estimate Std. Error   t value     Pr(>|t|)
# (Intercept) 19.742857   1.218217 16.206357 4.493289e-16
# cyl24        6.920779   1.558348  4.441099 1.194696e-04
# cyl28       -4.642857   1.492005 -3.111825 4.152209e-03

我们也可以通过了解其背后的理论来得到答案。也许这个答案更适合简历,但我想我应该把它发布在这里。

答案归结为了解其背后的统计数据。我们有两个随机变量的差异,我们想要获得其方差。

用数学术语来说,我们想要var(beta_{2vs1} -beta_{3vs1})。了解我们的基本统计数据后,我们知道这等于 var(beta_{2vs1}) +var(beta_{3vs1})-2*cov(beta_{2vs1},beta_{3vs1})

v <- vcov(m)
sqrt(v[2,2] + v[3,3] - 2*v[2,3])
# [1] 1.492005

关于r - lm 或 coxph 的未知对比度的方差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33712181/

相关文章:

python - sklearn |线性回归 |合身

r - 使用额外回归量预测 ARIMA 模型

r - 使用 RODBC sqlSave 将数据框从 R 写入 Teradata 中的表

r - 尽管有两组使用 ggplot2,但具有单条回归线的散点图

python - 如何根据 ODR 结果计算标准误差?

r - 目录中多个文件的循环线性模型

r - 如何通过我的数据拟合平滑曲线?

r - 如何将 abline() 添加到 pareto.chart()/barplot()?

r - plot.lm() : extracting numbers labelled in the diagnostic Q-Q plot

python - 使用 statsmodels.formula.api 的多项式回归