Useful STATA Commands

Useful STATA Commands

Xinya HAO (Hall)

Note: Built-in commands are marked with an asterisk (*).

Tools

  • ftools: Mata commands for factor variables.
  • gtools: A suite of commands that use hashes for a speedup over traditional stata commands.
  • github: Searching, installing, and managing Stata packages from GitHub.
  • halltool: A Stata toolbox (commands) developed by Hall.
  • unique: Unique values of a variable or group of variables.
  • egenmore: Extensions to command generate.

Data Cleaning

  • winsor2: Winsorizing or Trimming variables. Devekloped by Yujun Lian.

String Functions

  • *substr(s, n1, n2): The substring of s, starting at n1, for a length of n2.
  • *subinstr(s1, s2, s3, n): The first n occurrences in s1 of s2 will replaced with s3.
  • fdta variables, from(s1) to(s2): Replace si with s2 in all variables.
  • *regexm(s,re): Evaluates to 1 if regular expression re is satisfied by the ASCII string s; otherwise, 0.
  • *regexr(s, re, s2): Replaces the first substring within ASCII string s1 that matches regular expression re with ASCII string s2.

Analysis & Regressions

  • reghdfe: Regression with High-Dimensional Fixed Effects.
  • ppmlhdfe: Poisson Pseudo-Maximum Likelihood with High-Dimensional Fixed Effects.

Tabulation, Reporting, Visualization, and Documentation

  • esttab: Display and export formatted regression table.
  • asdoc: Send Stata output to Word / RTF format.

Others

  • *which: Display location of an ado-file.
  • adoedit: Open an ado-file.

Some usefule command blocks

Format long string variables

Format all long string variables to 30 characters while keeping the original format for short string variables.

1
2
3
4
5
6
7
8
9
10
local chmax 30
foreach var of varlist * {
local fmt: format `var'
local fmt: subinstr local fmt "%" "", all
local fmt: subinstr local fmt "s" "", all
cap local fmt = (`fmt' > `chmax')
if `fmt' == 1 {
cap format `var' %`chmax's
}
}

If you have halltool installed, you can do this:

1
fmtstr

Loop for multiple files in a folder

1
2
3
4
5
6
7
8
9
local folder_path = "./the_folder_path"
local file_type = ".dta"
local files: dir "`folder_path'" files "*`file_type'"
foreach file of local files {
local pref = substr("`file'", 1, 1)
if "`pref'" != "." {
* Do something
}
}

Remove a folder and its contents

1
2
3
4
5
6
7
8
local folder = "./the_folder_path"

*** On MacOS
shell rm -r "`folder'"
shell mv -f "`folder'" ~/.Trash

*** On Windows
shell rd "`folder'" /s /q

shell mv on MacOS is probably safer because you can resotre the folder from the Trash if you want to.

Comments