In Stata, how do I store the descriptive statistics of a variable in a macro?

In Stata, the .tabstat command computes aggregate statistics of variables such as mean and standard deviation, and its save option stores these statistics in a matrix. For example, to get the N, mean, and standard deviation of personal income, enter:

. tabstat income, stat(n mean sd) save

The stat() option specifies the aggregate statistics to be computed. N (the number of valid observations), mean, and standard deviation are stored in a matrix r(StatTotal). You may check for the presence of the matrix using the return list command. You can also list the values of the matrix by running matrix list r(StatTotal) as follows:

. return list

          r(StatTotal) :  3 x 1

. matrix list r(StatTotal)

To convert the special matrix into a typical matrix using the .matrix command, enter:

. matrix stats=r(StatTotal)

Finally, to convert a scalar, for example, the mean of the variable, into a macro, enter:

. local avg=stats[2,1]

If you want to save the matrix as a variable, enter the .svmat command instead:

. clear 
. svmat stats, name(var)   

You may clear memory before converting the matrix. Since the matrix has only one column (3x1), you may have one variable var1 with three observations for N, mean, and standard deviation.

If you have questions about using statistical and mathematical software at Indiana University, contact Research Analytics. Research Analytics is located on the IU Bloomington campus at Woodburn Hall 200; staff are available for consultation Monday-Friday 9am-noon and by appointment.

This is document atuo in the Knowledge Base.
Last modified on 2015-08-19 00:00:00.

Contact us

For help or to comment, email the UITS Support Center.