Stata: Extracting information from variable labels and names

This post discusses information contained in variable names of labels that might be useful for batch processing graphs. If one is processing a large dataset, then a good practice would be to have homogenized names for variables, for example v1, v2, v3, etc. so one can loop through them easily. Additionally, it is also good practice to store categorical information in value labels.

For example, a variable shows up as v1 with values 1, 2, 3, 4, 5 might be something

lab var v1 "Some description of the variable"

lab de v1lab 1 "category 1 description" 2 "category 2 description" 3 "category 3 description" etc

lab val v1 v1lab

The following two code blocks show how one can “pick” this information from the stored information and plug it in a graph for example:

Using value labels of a variable in graphs:

levelsof v1, local(lclname)

foreach x of local lclname {
    local t : label varlab `x'
    twoway line yvar xvar if v1==`x', ///
    title("`t'")
}

Using variable names in graphs

foreach x of varlist v1-v100 {
     local t : var label `x'
     twoway line v1 time, ///
     title("`t'")
}

NOTE: mind the spaces in locals. The semi-colon has to have a space.

Leave a Reply

Your email address will not be published.