Stata Code Fragments

Please Note: This page has been updated to Stata 12 as of May, 2012.
use, clear

* descriptive statistics by group or cell:

table a b, contents(freq mean y sd y) row col

* alternative method

egen grp=group(a b), label
tabstat y, by(grp) stat(n mean sd var)

* graph interaction/plot means by cell:

anova y a b a#b
margins a#b
marginsplot, x(a)  // place a on the x-axis
marginsplot, x(b)  // place b on the x-axis

* Levene's test of heterogeneity of variance:

robvar y, by(grp)  // W0 is the Levene's test

* visual check of normality

* histograms
histogram y, by(grp) normal

* kernal density plots
forvalues i = 1/8 {
  kdensity y if grp==`i', normal  name(cell`i', replace)

* normal probability plot
forvalues i = 1/8 {
  pnorm y if grp==`i', name(pnorm`i', replace)

* oneway anova:

anova y b

* factorial anova:

anova y a b a#b
anova y a b / a#b /        //  using interaction as error term 

* nested anova:

anova y a b|a            // using residual as error term for both a and b|a 
anova y a / b|a /        // using b|a as error term for a and residual for b|a 

* repeated measures anova:
* data are long

use, clear

* randomized block design
anova y b s, repeated(b)       
 mat lis e(Srep)                    // check variance-covariance matrix 
 * Tukeys test for additivity in randomized block designs: 
 anova y b s 
predict yhat 
generate ystar = (yhat - 5.375)^2      /*  5.375 is the grand mean */
anova y a s c.ystar  // if ystar is nonsignificant then model is additive

* split-plot factorial design
anova y a / s|a b a#b/, repeated(b)

* tests of simple main effects:

use, clear

anova y a b a#b
contrast a@b
contrast b@a

* pairwise comparisons:

pwcompare b,  mcompare(tukey) effects

* trend analysis
contrast p.b

* user defined contrasts:

contrast{b -3 1 1 1}  // 1 vs average of 2, 3, and 4

* analysis of covariance:

use, clear

anova y a c.x

graph slopes
sum x           // find min and max
margins a, at(x=(32 89))
marginsplot, x(x)

* adjusted cell means
margins a

* pairwise comparisons of adjusted means
pwcompare a,  mcompare(tukey) effects

* check homogeneity of slopes 
anova y a c.x a#c.x  

How to cite this page

Report an error on this page or leave a comment

The content of this web site should not be construed as an endorsement of any particular web site, book, or software product by the University of California.