0
votes

I have a categorical variable comprised of 12 levels with numerical values from 1 to 12.

Each one of these numerical values is assigned a label. For example, 1 = heart, 2 = brain, 3 = liver and so on. What i would like is to do is extract the label (heart, brain, liver) and place it into a local macro. Is this possible?

I have tried lots of different commands such as describe and codebook.

I have also tried the following:

levelsof var, local(diseases)

The above code gets the levels of the categorical variable var and stores them in the local macro diseases. However this only outputs the numerical values, that is 1,2,3,4, not the labels.

2

2 Answers

4
votes

Below is a flexible solution relying on macro extended functions:

sysuse auto, clear

levelsof foreign, local(levels)
local lab : value label foreign

foreach l of local levels {
    local all `all' `: label `lab' `l''
}

display "`all'"
Domestic Foreign

If you also want to keep the numerical values change the loop as follows:

foreach l of local levels {
    local all `all' `l' `: label `lab' `l''
}

display "`all'"
0 Domestic 1 Foreign
2
votes

The decode command is also helpful for this issue:

decode var, generate(labvar)
levelsof labvar, local(diseases) clean