首页 > 解决方案 > 基于多个条件的新变量(Stata)

问题描述

我的三个变量的结构如下:

pre_covid   change  post_covid
employed    Same         .
Housewif    Same         .
Business    diff      out of LF
employed    diff      unemployed
employed    Same         .
Housewif    Same         .

但是,对于那些自衰退开始以来状态没有改变的人,我不想错过(。),我想创建一个变量,如下所示 post-recession_status

pre_covid   change  post_covid   post_recession_status
employed    Same         .             employed 
Housewif    Same         .             Housewif 
Business    diff      out of LF        out of LF
employed    diff      unemployed       unemployed
employed    Same         .             employed    
Housewif    Same         .             Housewif 

covid前后类别的dataex如下:

 1 "employed", modify
 2 "Unemployed", modify
 3 "out of LF", modify
 4 "Housewife", modify
 5 "student", modify

更改变量的数据是:

Example generated by -dataex-. To install: ssc install dataex
clear
input float change 
2
2
1
1
end
label values change change 
label def change 1 "Different", modify
label def change 2 "Same", modify

标签: stata

解决方案


尽管进行了编辑,但您的数据示例在几个小细节上是不完整且不一致的:diffor different, Housewifor Housewife, Unemployedor unemployed,Business不是定义的值标签。

尽管如此,这仍然显示了一个类似的数据集作为示例(它来自编辑,一些额外的代码,然后是dataex),然后是一些令牌代码。

* Example generated by -dataex-. To install: ssc install dataex
clear
input long(pre_covid post_covid change)
1 . 2
4 . 2
6 3 1
1 2 1
1 . 2
4 . 2
end
label values pre_covid whatever
label values post_covid whatever
label def whatever 1 "employed", modify
label def whatever 4 "housewife", modify
label def whatever 6 "business", modify
label def whatever 2 "unemployed", modify
label def whatever 3 "out of LF", modify
label values change change
label def change 1 "different", modify
label def change 2 "same", modify

gen wanted = cond(change == 2, pre_covid, post_covid)
label val wanted whatever

list, sep(0)

     +-------------------------------------------------+
     | pre_covid   post_covid      change       wanted |
     |-------------------------------------------------|
  1. |  employed            .        same     employed |
  2. | housewife            .        same    housewife |
  3. |  business    out of LF   different    out of LF |
  4. |  employed   unemployed   different   unemployed |
  5. |  employed            .        same     employed |
  6. | housewife            .        same    housewife |
     +-------------------------------------------------+

推荐阅读