【问题标题】:Loop regression and save residuals in column循环回归并在列中保存残差
【发布时间】:2021-09-17 14:36:59
【问题描述】:

我有一个重复的横截面数据文件,我想循环运行多年来的 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。

【问题讨论】:

    标签: r statistics regression


    【解决方案1】:

    您应该始终通过创建一些或使用dput() 来提供示例数据。这是解决您的问题的基本 R 方法。首先是数据:

    set.seed(42)
    Year <- sample(2005:2007, 100, replace=TRUE)
    Y <- sample(8:18, 100, replace=TRUE)
    X <- sample(8:18, 100, 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
    

    【讨论】:

    • 非常感谢您的回复。您的代码运行良好!
    猜你喜欢
    • 2021-04-01
    • 1970-01-01
    • 2017-05-19
    • 1970-01-01
    • 2017-10-03
    • 1970-01-01
    • 2016-05-21
    • 2018-04-30
    • 1970-01-01
    相关资源
    最近更新 更多