1

In Stata I want to have a variable calculated by a formula, which includes multiplying by the previous value, within blocks defined by a variable ID. I tried using a lag but that did not work for me.

In the formula below the Y-1 is intended to signify the value above (the lag).

gen Y = 0 
replace Y = 1 if count == 1
sort ID
by ID: replace Y = (1+X)*Y-1 if count != 1


X          Y         count      ID
.          1          1          1
2          3          2          1
1          6          3          1
3         24          4          1
2         72          5          1
.          1          1          2
1          2          2          2
7         16          3          2
4

2 回答 2

1

您的代码可以更简洁一些。就是这样:

输入 X 计数 ID
. 1 1
2 2 1
1 3 1
3 4 1
2 5 1
. 1 2
1 2 2
7 3 2
结尾
gen Y = 计数 == 1
bysort ID (count) : 如果 count > 1 则替换 Y = (1 + X) * Y[_n-1]

虚拟(指标)变量的创建可以利用真或假表达式被评估为 1 或 0 的事实。

排序之前by和之后的by命令可以压缩为一个。请注意,我已说明在 , 的块内IDcount保持排序。

这实际上是一个评论,而不是另一个答案,但如果这样呈现就不太清楚了。

于 2013-10-03T08:03:39.190 回答
0

Y-1,公式中的滞后将被转换为如下所示。

gen Y = 0 
replace Y = 1 if count == 1
sort ID
by ID: replace Y = (1+X)*Y[_n-1] if count != 1
于 2013-10-03T05:41:46.623 回答