Updated: Jun 24
assert is a very useful command in Stata because it verifies if the expression provided is true. It not only tells Stata what to do but also what you can expect to find.
assert exp [if] [in] [, rc0 null fast]
To demonstrate, I will use the automobile dataset.
sysuse auto assert _N==74
Since there are 74 observations in the dataset, assert verifies that exp is true, the command produces no output.
assert foreign==0 | foreign==1
This means that confirm that variable foreign only takes values 0 or 1. It is true, therefore same as example 1, there is no output.
by foreign: assert price > 3000 if foreign==1
You can use by prefix when using assert. The above command verifies if the prices are all greater than $3000 for foreign cars. There is no output, which means that the assertion is true.
The do-file did not run to completion because it encountered a false assertion: variable rep78 is never missing. assert provides a count of the contradictions when an assertion is false. In this example, there are 5 contradictions. There are actually 5 missing values out of 74 observations. It also issued an error message with a return code of 9. The output from the false assertion is helpful, as it requires you to review the output to spot the error.
The only difference between this code and the one in the previous example, is that I added the fast option in the end. In the previous example, we received a count of the number of observations where each assertion was false. However, if you only want to know whether or not the assertion is true, you can specify the fast option. It can reduce the amount of time required to check the assertion, by telling Stata to stop checking the assertion when it encounters the first case where it is false, that's why you don't get a count of the contradictions.
To learn more on the Stata commands, please have a look at the book Data Management Using Stata