在 foreach 循环中,如何找到相应变量左侧两列的平均值?

In a foreach loop how do I find the average of the two columns to the left of the respective variable?

在 Stata 中:到目前为止我已经

foreach i of varlist v8 - v23 {
     gen v_`i' = (`i'[_n-2]*`i'[_n-3] * `i'[_n-4])/3
}

但这不是这样做的。

这是对以前的观察结果取平均值,而不是以前的变量。

你的问题标题是关于两列(意思是变量)的平均值。您的代码看起来像是试图对三个变量的平均值进行编码。我会 运行 第二个

你的变量运行8到23;所以第一个平均值是位置 11 作为 8、9、10 的平均值。

forval j = 11/23 {
    local 3 = `j' - 3 
    local 2 = `j' - 2 
    local 1 = `j' - 1 
    generate v_`j' = (v`3' + v`2' + v`1') / 3 
}

这可以压缩成更少的行,但清楚地显示一些结构似乎更重要。

如果 8 到 23 代表不同的时间,并且在许多其他情况下也是如此,那么 reshape long 之后你会过得更好。