Remove blanks from string variables in Stata

When dealing with string variables in Stata, blanks spaces can make it difficult to identify values. For example, if a variable contains " Arizona", a command that contains an if command such as ... if state="Arizona" won’t detect this observation.

To trim blank spaces at the beginning or the end of the value, Stata has different built-in functions:

* Removes blanks at beginning and end
replace state=trim(state)
* Removes blanks at beginning only
replace state=ltrim(state)
* Removes blanks at end only
replace state=rtrim(state)

To remove blanks between words or numbers of the string variables, one can use the subinstr command:

* Removes all blanks in string (irrespective of place)
replace state=subinstr(state," ","",.)

Leave a Reply