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

问题描述 投票:0回答:2

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

例如:

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

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

label stata stata-macros
2个回答
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

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
        }
}
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.