在一行中列出变量名称,标签和所有值标签

时间:2019-03-26 10:55:32

标签: label stata stata-macros

我想为数据集中的每个变量在一行上列出变量的名称,标签以及所有值和值标签。

例如:

foreign, Car type, 0 Domestic 1 Foreign

我设法编写了一些代码来做到这一点,但是它只显示了数据集中使用的值标签:

sysuse auto, clear

foreach var of varlist * {
    local _check: val l `var'
    if `"`_check'"' != "" {
        quietly fre `var'
        di "`var'" char(44) `"`: var label `var' '"' char(44) as result r(lab_valid)
        continue    
        }
    else{
        di "`var'" char(44) `"`: var label `var' '"'    
        continue
        }
}

如果数据不包含fre,则社区贡献命令0 Domestic仅包含1 Foreign

有更简单的方法来显示值标签,但都可以在不同的行上显示它们。

2 个答案:

答案 0 :(得分:1)

无需安装和使用社区贡献的命令fre

您可以使用内置的扩展宏功能执行所需的操作:

foreach var of varlist * {
    local _check: value label `var'
    if `"`_check'"' != "" {
        quietly label list `_check'
        local vlabels
        forvalues i = `r(min)' / `r(max)' {
            local vlabels `vlabels' `i' `: label `_check' `i''
        }
        display "`var', " `"`: var label `var' ', "' "`vlabels'"
        continue    
    }
    else {
        display "`var', " `"`: var label `var' '"'    
        continue
    }
}

在Stata的auto玩具数据集上使用上述代码片段,您将获得:

make, Make and Model
price, Price
mpg, Mileage (mpg)
rep78, Repair Record 1978
headroom, Headroom (in.)
trunk, Trunk space (cu. ft.)
weight, Weight (lbs.)
length, Length (in.)
turn, Turn Circle (ft.) 
displacement, Displacement (cu. in.)
gear_ratio, Gear Ratio
foreign, Car type, 0 Domestic 1 Foreign

即使您在foreign中放了一个关卡,它也将起作用。

例如:

keep if foreign == 1

make, Make and Model
price, Price
mpg, Mileage (mpg)
rep78, Repair Record 1978
headroom, Headroom (in.)
trunk, Trunk space (cu. ft.)
weight, Weight (lbs.)
length, Length (in.)
turn, Turn Circle (ft.) 
displacement, Displacement (cu. in.)
gear_ratio, Gear Ratio
foreign, Car type, 0 Domestic 1 Foreign

答案 1 :(得分:0)

使用include中的选项fre解决了希望将所有值标签都列出一行的问题,甚至是那些未在数据中使用的值标签。

例如:

foreach var of varlist * {  
    local _check: val l `var'
    if `"`_check'"' != "" {
        quietly fre `var', include
        di "`var'" char(44) `"`: var label `var' '"' char(44) as result r(lab_valid)
        continue    
        }
    else{
        di "`var'" char(44) `"`: var label `var' '"'    
        continue
        }
}