温馨提示:本文翻译自stackoverflow.com,查看原文请点击:stata - Setting value of variable within each group based on binary choice

stata - 根据二进制选择在每个组中设置变量的值

发布于 2020-04-03 23:27:51

考虑下面的数据示例,最初我具有groupchoice变量:

obs    group  choice  need   coding

1      1      0       car     train
2      1      1       car     car
3      1      0       car     bus
--------------------------------------
4      2      0       bus     train
5      2      0       bus     car
6      2      1       bus     bus
--------------------------------------
7      3      1       train   train
8      3      0       train   car
9      3      0       train   bus
--------------------------------------
10     5      0       car     train
11     5      1       car     car
12     5      0       car     bus
--------------------------------------

如果编码choice如上所述,我如何生成变量need

我阅读了一个相关的问题和一些论坛文章,但未能使其适应我的情况。

查看更多

提问者
garej
被浏览
26
Pearly Spencer 2020-01-31 19:56

以下对我有用:

clear
input group choice
1 0 
1 1
1 0
2 0
2 0 
2 1
3 1
3 0 
3 0
5 0
5 1
5 0
end

bysort group: generate coding = _n
label define coding 1 "train" 2 "car" 3 "bus"
label values coding coding

bysort group: generate tag = coding if choice == 1
egen need = max(tag), by(group)
label values need coding

drop tag

结果:

list, sepby(group)

     +---------------------------------+
     | group   choice   coding    need |
     |---------------------------------|
  1. |     1        0    train     car |
  2. |     1        1      car     car |
  3. |     1        0      bus     car |
     |---------------------------------|
  4. |     2        0    train     bus |
  5. |     2        0      car     bus |
  6. |     2        1      bus     bus |
     |---------------------------------|
  7. |     3        1    train   train |
  8. |     3        0      car   train |
  9. |     3        0      bus   train |
     |---------------------------------|
 10. |     5        0    train     car |
 11. |     5        1      car     car |
 12. |     5        0      bus     car |
     +---------------------------------+