Table of descriptives

Posted by Didier

This illustrates ways to make a tables of descriptives (mean or something else) for many variables (say wage, tenure, education, …) and several groups (say males and female). Neither summarize or tabstat are useful if the variables are many. With summarize, you would need to cut, paste and edit the output in e.g. Excel. With tabstat, the tabel would be too wide.

sysuse auto, clear
global vars "price mpg rep78 headroom trunk weight length"

With summarize: This is the info I want, but I want it in columns with col 1 Domestic and col 2 Foreign

bys foreign: su $vars, sep(0)

With tabstat: tabstat does not help, for it puts Foreign and Domestic in the rows

tabstat $vars, by(foreign) s(mean) format(%6.2f)

With tabout: tabout does the same as tabstat, but has the advantage of saving the tabulation

tabout foreign using c:\temp\test.txt, replace ///
c(mean price mean mpg mean rep78 ///
mean headroom mean trunk mean weight mean length) ///
sum f(2c)

With collapse, xpose and list: this helps a little, but is not really good looking

preserve
collapse $vars, by(foreign)
xpose, clear varname format(%6.2f)
list, clean
save c:\temp\test, replace
restore

With collapse, reshape and tabel: OK, it takes a little more writing, but the table is ready to be copy pasted, and a data set with the content of the table could be saved

preserve
collapse $vars, by(foreign)
local n : word count $vars
forvalues i = 1 / `n' {
local help : word `i' of $vars
gen x`i' = `help'
drop `help'
}
reshape long x, i(foreign)
lab def _j 1 "price" 2 "mpg" 3 "rep78" 4 "headroom" 5 "trunk" 6 "weight" 7 "length"
lab val _j _j
table _j foreign, c(mean x) format(%6.2f)
save c:\temp\test, replace
restore

Now, redo the same but also generate a column for the total of Domestic and Foreign

preserve
collapse $vars
local n : word count $vars
forvalues i = 1 / `n' {
local help : word `i' of $vars
gen x`i' = `help'
drop `help'
}
gen foreign = 3
save c:\temp\total, replace
restore
preserve
collapse $vars, by(foreign)
local n : word count $vars
forvalues i = 1 / `n' {
local help : word `i' of $vars
gen x`i' = `help'
drop `help'
}
append using c:\temp\total
reshape long x, i(foreign)
lab def origin 3 "Total", add
lab def _j 1 "price" 2 "mpg" 3 "rep78" 4 "headroom" 5 "trunk" 6 "weight" 7 "length"
lab val _j _j
table _j foreign, c(mean x) format(%6.2f)
save c:\temp\test, replace
restore

Leave a Reply