用 R 改变回归模型中的对比

Posted

技术标签:

【中文标题】用 R 改变回归模型中的对比【英文标题】:Changing the contrasts in regression models with R 【发布时间】:2017-02-02 14:10:25 【问题描述】:

我有一个关于在 R 中估计回归模型的问题。我有以下数据(示例):

Year   XY
2002    5  
2003    2
2004    4
2005    8
2006    3
2007    5
2008   10

the regression model I want to estimate is: 
XY = B0 + Y2005 + Y2006 + Y2007 + Y2008 + e 

其中 Y2005、Y2006、Y2007 和 Y2008 是年度指标变量,对于 2005、2006、2007、2008 年取值为 1,否则为 0。

我需要做的是比较(XY)在2005年、2006年、2007年和2008年的值与(XY)在(2002-2004)期​​间的平均值。

我希望您能帮助我解决这个问题,并提前感谢您的帮助。

【问题讨论】:

【参考方案1】:
DF <- read.table(text = "Year   XY
                 2002    5  
                 2003    2
                 2004    4
                 2005    8
                 2006    3
                 2007    5
                 2008   10", header = TRUE)

DF$facYear <- DF$Year
DF$facYear[DF$facYear < 2005] <- "baseline"
DF$facYear <- factor(DF$facYear)

#make sure that baseline is used as intercept:
DF$facYear <- relevel(DF$facYear, "baseline")

fit <- lm(XY ~ facYear, data = DF)
summary(fit)
#Coefficients:
#            Estimate Std. Error t value Pr(>|t|)  
#(Intercept)   3.6667     0.8819   4.158   0.0533 .
#facYear2005   4.3333     1.7638   2.457   0.1333  
#facYear2006  -0.6667     1.7638  -0.378   0.7418  
#facYear2007   1.3333     1.7638   0.756   0.5286  
#facYear2008   6.3333     1.7638   3.591   0.0696 .

【讨论】:

感谢@Roland 的帮助

以上是关于用 R 改变回归模型中的对比的主要内容,如果未能解决你的问题,请参考以下文章