help levelsof
-------------------------------------------------------------------------------
Title
[P] levelsof -- Levels of variable
Syntax
levelsof varname [if] [in] [, options]
options description
-------------------------------------------------------------------------
clean display string values without compound double
quotes
local(macname) insert the list of values in the local macro
macname
missing include missing values of varname in calculation
separate(separator) separator to serve as punctuation for the values
of returned list; default is a space
-------------------------------------------------------------------------
Description
levelsof displays a sorted list of the distinct values of varname.
Options
clean displays string values without compound double quotes. By default,
each distinct string value is displayed within compound double
quotes, as these are the most general delimiters. If you know that
the string values in varname do not include embedded spaces or
embedded quotes, this is an appropriate option. clean does not
affect the display of values from numeric variables.
local(macname) inserts the list of values in local macro macname within
the calling program's space. Hence, that macro will be accessible
after levelsof has finished. This is helpful for subsequent use,
especially with foreach.
missing specifies that missing values of varname should be included in
the calculation. The default is to exclude them.
separate(separator) specifies a separator to serve as punctuation for the
values of the returned list. The default is a space. A useful
alternative is a comma.
Remarks
levelsof serves two different functions. First, it gives a compact
display of the distinct values of varname. More commonly, it is useful
when you desire to cycle through the distinct values of varname with
(say) foreach; see [P] foreach. levelsof leaves behind a list in
r(levels) that may be used in a subsequent command.
levelsof may hit the limits imposed by your Stata. However, it is
typically used when the number of distinct values of varname is modest.
The terminology of levels of a factor has long been standard in
experimental design.
Examples
. sysuse auto
. levelsof rep78
. display "`r(levels)'"
. levelsof rep78, miss local(mylevs)
. display "`mylevs'"
. levelsof rep78, sep(,)
. display "`r(levels)'"
Showing value labels when defined:
. levelsof factor, local(levels)
. foreach l of local levels {
. di "-> factor = `: label (factor) `l''"
. whatever if factor == `l'
. }
Saved results
levelsof saves the following in r():
Macros
r(levels) list of distinct values
Also see
Manual: [P] levelsof
Help: [P] foreach; [D] codebook, [D] inspect, [R] tabulate oneway