【问题标题】:Counting groups but skipping empty in Stata计数组但在Stata中跳过空
【发布时间】:2017-03-01 07:40:58
【问题描述】:

我的数据是这样的

clear
input str5 name long id str3 place byte count str5 name_label byte(counting counting_ideal)
"Steve" 110821105 "ABC" 1 "Steve" 1 1
"Steve" 110821105 "ABC" 1 "Steve" 1 1
"Steve" 110821105 "ABC" 1 "Steve" 1 1
"Steve" 110821105 "ABC" 1 "Steve" 1 1
"Steve" 110821105 "ABC" 1 "Steve" 1 1
"Steve" 110821105 "ABC" 1 "Steve" 1 1
"Jeff"  110711108 "ABC" 0 ""      2 .
"Jeff"  110711114 "ABC" 0 ""      3 .
"Jeff"  110711104 "ABC" 0 ""      4 .
"Jess"  110712102 "ABC" 1 "Jess"  5 2
"Jess"  110712102 "ABC" 1 "Jess"  5 2
"Jess"  110712102 "ABC" 1 "Jess"  5 2
"Jess"  110712102 "ABC" 1 "Jess"  5 2
"Jess"  110712102 "ABC" 1 "Jess"  5 2
"Jess"  110712102 "ABC" 1 "Jess"  5 2
"Jess"  110712102 "ABC" 1 "Jess"  5 2
"Jess"  110712102 "ABC" 1 "Jess"  5 2
"Jess"  110712102 "ABC" 1 "Jess"  5 2
"Jess"  110712102 "ABC" 1 "Jess"  5 2
"Jess"  110712102 "ABC" 1 "Jess"  5 2
"Jess"  110712102 "ABC" 1 "Jess"  5 2
"Jess"  110712102 "ABC" 1 "Jess"  5 2
"Matt"  110712101 "ABC" 1 "Matt"  6 3
"Matt"  110712101 "ABC" 1 "Matt"  6 3
"Matt"  110712101 "ABC" 1 "Matt"  6 3
"Matt"  110712101 "ABC" 1 "Matt"  6 3
"Matt"  110712101 "ABC" 1 "Matt"  6 3
"Matt"  110712101 "ABC" 1 "Matt"  6 3
"Matt"  110712101 "ABC" 1 "Matt"  6 3
end

如何生成counting_ideal 列?请注意,我有几个place 变量,因此我要执行的命令应指定place=="ABC"

我试过了:

encode name if count>0 & place=="ABC", gen(counting) 

..但这会生成一个连续计数,不会忽略空的“name_label”观察。

【问题讨论】:

  • 感谢数据示例。 [CODE][/CODE] 标记在 Statalist 上需要,但在其他地方不需要:dataex (SSC) 的帮助讨论了这个小细节。
  • 关于“几个”place 变量的详细信息根本不清楚。我只看到一个这样的变量。也许您的意思是 place 变量在整个数据集中有几个不同的值。

标签: stata


【解决方案1】:

鉴于您的(欢迎)数据示例

gen wanted = cond(name_label == "", ., sum(name_label != name_label[_n-1] & name_label != "")) 

伪代码解构:

if name_label is empty { 
   return missing 
} 
else return the count of runs of name_labels so far 

这里的运行只是一系列相同的非缺失值。因此,我们根据与之前的名称标签不同(并且不为空)的条件来识别开始运行的新名称标签:

name_label != name_label[_n-1] & name_label != "" 

这是一个真假表达式,计算为 1 或 0。sum() 产生的累积和在遇到 1 时增加 1,否则在遇到 0 时保持不变,这正是计数的含义.

in this paper 讨论了使用此类跑步或法术背后的原则。

你对place变量的规定并没有真正解释,但是如果你想为place的不同值分别编号,那么整个操作应该完成

gen long obs = _n 
bysort place (obs): gen wanted = ... 

【讨论】:

    猜你喜欢
    • 2021-12-27
    • 1970-01-01
    • 2017-05-16
    • 2021-07-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多