计算连续的1 [英] Calculating consecutive ones
本文介绍了计算连续的1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有id
和D
。D
为1或0。
我要为每个id
计算"连续一"。
连续1计算每个id
中D
中的连续1的个数。
id year D CO
1 1990 1 1
1 1991 1 2
1 1992 0 0
1 1993 0 0
1 1994 1 1
1 1995 0 0
1 1996 1 1
1 1997 1 2
2 1990 1 1
2 1991 0 0
2 1992 0 0
2 1993 1 1
2 1994 1 2
2 1995 1 3
我做了一个流动总和,希望这能成为一块垫脚石。
bysort id (year): gen runningsumD=sum(D)
然后我也试了
bysort id (year): replace CO=D[_n-1]+D if D!=0
但这又一次没有给我想要的。
推荐答案
现在《统计学家》和《统计杂志》中都有大量关于类似问题的讨论。了解一些search
的关键字是很有帮助的,例如法术或运行都是由1的连续值定义的。
因此,此问题中咒语开始的条件是感兴趣的值为1,先前的值为0或这是面板的开始。(第二种可能性在编码时很容易被忽视。)该关节条件给你一个指示变量,在咒语开始时为1,否则为0。那么,你想要的是在观察到同样的咒语时,提高这个指标。
以下是您的数据示例的示例代码和结果:
clear
input id year D CO
1 1990 1 1
1 1991 1 2
1 1992 0 0
1 1993 0 0
1 1994 1 1
1 1995 0 0
1 1996 1 1
1 1997 1 2
2 1990 1 1
2 1991 0 0
2 1992 0 0
2 1993 1 1
2 1994 1 2
2 1995 1 3
end
bysort id (year) : gen wanted = D == 1 & (_n == 1 | D[_n-1] == 0)
by id: replace wanted = wanted[_n-1] + 1 if D == 1 & wanted == 0
list, sepby(id)
+-----------------------------+
| id year D CO wanted |
|-----------------------------|
1. | 1 1990 1 1 1 |
2. | 1 1991 1 2 2 |
3. | 1 1992 0 0 0 |
4. | 1 1993 0 0 0 |
5. | 1 1994 1 1 1 |
6. | 1 1995 0 0 0 |
7. | 1 1996 1 1 1 |
8. | 1 1997 1 2 2 |
|-----------------------------|
9. | 2 1990 1 1 1 |
10. | 2 1991 0 0 0 |
11. | 2 1992 0 0 0 |
12. | 2 1993 1 1 1 |
13. | 2 1994 1 2 2 |
14. | 2 1995 1 3 3 |
+-----------------------------+
阅读和节目单可能包括
SJ-15-1 dm0079 . . . . . . . . . . . . . . . Stata tip 123: Spell boundaries
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . N. J. Cox
Q1/15 SJ 15(1):319--323 (no commands)
shows how to identify spells
SJ-7-2 dm0029 . . . . . . . . . . . . . . Speaking Stata: Identifying spells
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . N. J. Cox
Q2/07 SJ 7(2):249--265 (no commands)
shows how to handle spells with complete control over
spell specification
最后提到的.pdf可在http://www.stata-journal.com/sjpdf.html?articlenum=dm0029
免费获取.pdf将在Stata Journal18(1)出版时免费提供。
tsspell
(SSC)是使用刚才引用的2007年论文中描述的原理的基本工具。tsspell
因此为您提供了一个搜索Statist讨论的不可预测的搜索词。
https://www.stata.com/support/faqs/data-management/identifying-runs-of-consecutive-observations/也与相关问题相关。
这篇关于计算连续的1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文