Stata中含多类比率的变量统计汇总计算技术问询
Hey there! As a Stata newbie, I totally get how frustrating it can be to tack those custom ratios onto your summary stats when you already have the basic quantile table sorted. Let’s walk through exactly how to calculate and include the coefficient of variation, 75%/25% quantile ratio, 95%/5% quantile ratio, and second largest/second smallest value ratio in your results.
Step 1: Set Up with estpost (Install estout First!)
First, make sure you have the estout package installed—it’s essential for collecting and customizing summary stats. Run this if you haven’t already:
ssc install estout
We’ll use estpost to gather all the raw stats we need: mean, standard deviation, quantiles, and extreme values. For multiple variables, a loop will save you tons of repetitive code.
Step 2: Full Loop to Calculate & Store Custom Ratios
Copy this code, replace the variable list with your own dataset’s variables, and run it:
* Clear any existing stored estimates to avoid conflicts estimates clear * Replace this with your actual variable names local target_vars var1 var2 var3 * Loop through each variable to compute stats foreach var of local target_vars { * Collect detailed summary statistics estpost summarize `var', detail * 1. Coefficient of Variation (CV) = (Std Dev / Mean) * 100 estadd scalar cv = (e(sd_`var')/e(mean_`var'))*100 * 2. 75th / 25th Quantile Ratio estadd scalar q75q25 = e(p75_`var')/e(p25_`var') * 3. 95th / 5th Quantile Ratio estadd scalar q95q5 = e(p95_`var')/e(p5_`var') * 4. Second Largest / Second Smallest Value Ratio tempvar sorted gen `sorted' = `var' drop if missing(`sorted') // Remove missing values to avoid errors sort `sorted' local second_min = `sorted'[2] local second_max = `sorted'[_N-1] estadd scalar secmaxsecmin = `second_max'/`second_min' * Store results for this variable estimates store stats_`var' }
Quick Explanations:
tempvarcreates a temporary variable that won’t clutter your dataset.- We drop missing values before calculating the second min/max to ensure valid observations are used.
estadd scalarattaches each custom ratio to the stored statistics for that variable.
Step 3: Generate a Clean Final Table
Use esttab to output all your desired stats in a readable table:
esttab stats_*, /// cells("mean cv q75q25 q95q5 secmaxsecmin") /// label /// title("Custom Summary Statistics") /// varwidth(20) /// format(%9.2f) /// replace stats_table.txt // Remove "stats_table.txt" if you don't want to save to a file
What Each Argument Does:
cells(...): Lists which stats to display in the table.label: Uses variable labels instead of raw variable names for clarity.format(%9.2f): Formats numbers to 2 decimal places for consistency.replace stats_table.txt: Saves the table to a text file (adjust the filename as needed).
Test with Sample Data
Want to try this before using your own dataset? Load Stata’s built-in auto dataset and run the loop with these variables:
sysuse auto, clear local target_vars price mpg weight
Troubleshooting Tips
- If
estpostthrows an error, double-check thatestoutis installed. - If you get missing value warnings, confirm the
drop if missing(sorted')` line is included—it filters out invalid observations.
内容的提问来源于stack exchange,提问作者Nico3105

