我想要generate一个变量max_count,其中对于给定的组ID,如果当前年的count值高于前一年,那么max_count获取当前年份的值。本年度的价值将适用于以后的年份,直到出现高于当年的数值为止。例如,在以下ID 2的示例中,2001年的count值为10,但随后几年(2002年和2003年)的数值小于10 (即2和4),因此2002年和2003年的数值为10 (2001年之后的最高值)。
我使用了这个Stata代码,但它不起作用:
bysort id (Year): gen max_count=max(count, count[_n-1])最高价值仅适用于紧接着的年份,而不适用于随后的所有年份。
ID Year count max_count
1 2000 5 5
1 2001 0 5
1 2002 3 5
1 2003 7 7
2 2000 5 5
2 2001 10 10
2 2002 2 10
2 2003 4 10
3 2000 2 2
3 2001 5 5
3 2002 9 9
3 2003 6 9发布于 2021-03-23 09:31:17
clear
input ID Year count max_count
1 2000 5 5
1 2001 0 5
1 2002 3 5
1 2003 7 7
2 2000 5 5
2 2001 10 10
2 2002 2 10
2 2003 4 10
3 2000 2 2
3 2001 5 5
3 2002 9 9
3 2003 6 9
end
bysort ID (Year) : gen wanted = count[1]
by ID : replace wanted = max(wanted[_n-1], count) if _n > 1
list, sepby(ID)
+---------------------------------------+
| ID Year count max_co~t wanted |
|---------------------------------------|
1. | 1 2000 5 5 5 |
2. | 1 2001 0 5 5 |
3. | 1 2002 3 5 5 |
4. | 1 2003 7 7 7 |
|---------------------------------------|
5. | 2 2000 5 5 5 |
6. | 2 2001 10 10 10 |
7. | 2 2002 2 10 10 |
8. | 2 2003 4 10 10 |
|---------------------------------------|
9. | 3 2000 2 2 2 |
10. | 3 2001 5 5 5 |
11. | 3 2002 9 9 9 |
12. | 3 2003 6 9 9 |
+---------------------------------------+详细讨论了如何在这个斯塔塔常见问题中获得这样的记录(到目前为止最大或最小的记录是“记录”,就像在体育中一样)。
对于单行解决方案,请从SSC安装rangestat,然后
rangestat (max) WANTED = count, int(Year . 0) by(ID) 记录何时发生的问题自然是相关的:
by ID : gen when = Year[1]
by ID : replace when = cond(wanted > wanted[_n-1], Year, when[_n-1]) if _n > 1https://stackoverflow.com/questions/66760105
复制相似问题