Princeton Stata Tutorial Study Notes 4

These notes are for Section Programming.

Macros

local name [=] text

* example for regression control variables
local controls age agesq education income
regress outcome treatment `controls'

* example for dummy variables
local age "age20to24 age25to29 age30to34 age35to39 age40to44 age45to49"
regress ceb `age' urban

* macro with equal sign
sysuse auto, clear
desc
summ
quietly regress mpg weight

local rsqf e(r2) // stores the formula, like function
local rsqv = e(r2) // stores the result, like return of function

di `rsqf' 
di `rsqv'

quietly regress mpg weight foreign
di `rsqf'
di `rsqv'

Looping

* template for looping over the sequence of numbers
forvalues number = sequence {
    ... body of loop using `number' ...
}

* creating dummy
forvalues bot = 20(5)45 {
    local top = `bot' + 4
    gen age`bot'to`top' = age >= `bot' & age <= `top'
}

* template for looping over list
foreach item in a-list-of-things {
    ... body of loop using `item' ...
}

foreach level in 2 6 12 {
    ... do something with `level' ...
}

* template for specialized list
foreach varname of varlist list-of-variables {
    ... body of loop using `varname' ...
}

foreach varname of newlist list-of-new-variables {
    ... body of loop using `varname' ...
}

foreach control of local controls {
    display "`control'"
}

foreach control of global controls {
    display "`control'"
}

foreach year of numlist 1980 1985 1995 {
    display "`year'"
}

* conditional execution
if expression {
    ... commands to be executed if expression is true ...
}
else {
    ... optional block to be executed if expression is false ...
}

forvalues iter=1/10 {
    display "`iter'"
    if `iter' >= 5 continue, break
}

Writing Commands

* program without parameter
capture program drop sign
program define sign
    version 9.1
    display as text "Johann Huang "
    display "{txt}{hline 62}"
end
sign


* program with parameter
capture program drop echo
program define echo
    version 9.1
    display as text "`0'"
end
echo Johann Huang Said Something

* compound quotes, can save as `echo.ado` file to make accessible globally
program define echo
    version 9.1
    if `"`0'"' != "" display as text `"`0'"'
end
which echo

* positional arguments
capture program drop echo
program define echo
    version 9.1
    while "`1'" != "" {
        display `"`1'"'
        mac ⇧
    }
end

* skipped from `4.3.5 Using Stata Syntax` since no need to know currently

More

help forvalues
help smcl
help trace
help do

set trace on
set trace off

Change Log


* cached version, generated at 2018-12-02 20:42:53 UTC.

Subscribe by RSS