【问题标题】:Stata Wide to Long Reshape - Apply wide variable labels as long value labelsStata Wide to Long Reshape - 应用宽变量标签作为长值标签
【发布时间】:2021-01-05 20:58:51
【问题描述】:

我有宽数据,其中 ID 是唯一标识符,还有一系列变量 branch1 - branch3 我想从宽数据进行转换。来自广泛数据的变量标签,我认为需要作为值标签应用,所以我可以保留分支名称。

clear
input id branch1 branch2 branch3
1 0 1 1 
2 1 1 1 
3 0 0 0 
4 1 0 1 
5 0 1 0
end

* Labels are already come with the data file, just creating some for example
label variable branch1 "Branch Name A"
label variable branch2 "Branch Name B"
label variable branch3 "Branch Name C"

* Reshape to long
reshape long branch, i(id) j(brn_name)

从这里我想要的输出是:


id   brn_name   branch   branch_value
1          1        0    Branch Name A
1          2        1    Branch Name B
1          3        1    Branch Name C
2          1        1    Branch Name A
2          2        1    Branch Name B
2          3        1    Branch Name C
3          1        0    Branch Name A
3          2        0    Branch Name B
3          3        0    Branch Name C
4          1        1    Branch Name A
4          2        0    Branch Name B
4          3        1    Branch Name C
5          1        0    Branch Name A
5          2        1    Branch Name B
5          3        0    Branch Name C

【问题讨论】:

    标签: stata


    【解决方案1】:

    由于您想要的变量branch_value 基本上是brn_name 值的标签,因此您可以利用Stata 的功能来获得带有值标签的数字变量。

    如果您不执行最后两行,下面的代码将执行此操作。否则,执行最后两行以获得您要求的结果。

    clear
    input id branch1 branch2 branch3
    1 0 1 1 
    2 1 1 1 
    3 0 0 0 
    4 1 0 1 
    5 0 1 0
    end
    
    * Labels are already come with the data file, just creating some for example
    label variable branch1 "Branch Name A"
    label variable branch2 "Branch Name B"
    label variable branch3 "Branch Name C"
    
    // Build value label
    foreach var of varlist branch* {
        local branch_nr: subinstr local var "branch" ""
        label define branches_label `branch_nr' "`:variable label `var''", add
    }
    
    // Reshape
    reshape long branch, i(id) j(brn_name)
    
    // Assign label to brn_name
    label values brn_name branches_label
    
    // Possibly stop here!
    
    // Decode value labels
    decode brn_name, gen(branch_value)
    label values brn_name .
    

    【讨论】:

      猜你喜欢
      • 2015-11-21
      • 2022-11-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多