Skip to content

Instantly share code, notes, and snippets.

@btskinner
Last active May 6, 2023 16:58
Show Gist options
  • Save btskinner/869b3658230cc3661c2c to your computer and use it in GitHub Desktop.
Save btskinner/869b3658230cc3661c2c to your computer and use it in GitHub Desktop.
A code snippet to create dummy variables from labeled categorical variables that attaches the appropriate label to the new variables.
// STATA CODE SNIPPET TO MAKE DUMMY VARIABLES FROM CATEGORICAL
// VARIABLES WHILE RETAINING VALUE LABELS
// Benjamin Skinner
// Vanderbilt University
// PURPOSE
// Sometimes we want dummy variables but instead have categorical
// variables. While it's no big deal to create dummy variables from
// categorical variables, relabeling those dummies can be a total pain
// if there are a lot of them. This code allows you to insert
// categorical variables in the local `makedummy' and have them
// (1) turned into dummies that
// (2) retain their variable and value label.
// It is robust to categorical variables, whether they start at 0 or 1.
// BEGIN CODE SNIPPET
// dummy for categorical variables
#delimit;
local makedummy
// place categorical vars here
;
#delimit cr
local i = 1
foreach var of local makedummy {
// get overall label
local l`var' : variable label `var'
// get all values for var
levelsof `var', local(`var'_levels)
// need for later
local frst = substr("`r(levels)'",1,1)
// store values individually
foreach val of local `var'_levels {
local `var'vl`val' : label `var' `val'
}
// create dummies from var
tab `var', gen(d`var')
// for each new dummy ...
foreach dum of varlist d`var'* {
local num = substr("`dum'",-1,1)
foreach value of local `var'_levels {
// if 0/1 binary or cat. that starts with 0
if `frst' == 0 {
// label new dummy with old value
if `num' == `value' + 1 {
label variable `dum' "`l`var'' - ``var'vl`value''"
}
}
// if 1/2 binary or cat. that starts with 1
if `frst' == 1 {
// label new dummy with old value
if `num' == `value' {
label variable `dum' "`l`var'' - ``var'vl`value''"
}
}
}
// add dummy var name to local
local dumvarlist `dumvarlist' `dum'
}
}
describe `dumvarlist'
// END CODE SNIPPET
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment