问题描述
我有一个重复的横截面数据文件,我想多年来循环运行 OLS 回归,然后将残差保存在新列中。
我的数据如下:
Y X Year
150 10 2005
120 11 2005
200 11 2006
180 15 2006
310 12 2007
280 09 2007
Stata 中的等效函数是:
forvalues i = 2005(1)2007{
qui reg Y X if year==`i'
predict res`i' if year==`i',r
}
总而言之,我需要将上面的代码从 Stata 转换为 R。
解决方法
您应该始终通过创建一些或使用 dput()
来提供示例数据。这是解决您问题的基本 R 方法。先上数据:
set.seed(42)
Year <- sample(2005:2007,100,replace=TRUE)
Y <- sample(8:18,replace=TRUE)
X <- sample(8:18,replace=TRUE)
dat <- data.frame(Y,X,Year)
现在分析:
dat.spt <- split(dat,dat$Year)
res.spt <- lapply(dat.spt,function(k) residuals(lm(Y~X,k)))
dat.res <- data.frame(unsplit(dat.spt,Year),res=unsplit(res.spt,Year))
head(dat.res)
# Y X Year res
# 1 15 16 2005 0.7597518
# 2 14 13 2005 0.8477988
# 3 13 15 2005 -0.8775658
# 4 8 8 2005 -3.3387895
# 5 12 13 2006 -0.0399568
# 6 16 18 2006 2.3158747