Regression with Stata
Chapter 1 - Simple and Multiple Regression

Chapter Outline
    1.0 Introduction
    1.1 A First Regression Analysis
    1.2 Examining Data
    1.3 Simple linear regression
    1.4 Multiple regression
    1.5 Transforming variables
    1.6 Summary
    1.7 Self assessment
    1.8 For more information

1.0 Introduction

This book is composed of four chapters covering a variety of topics about using Stata for regression. We should emphasize that this book is about "data analysis" and that it demonstrates how Stata can be used for regression analysis, as opposed to a book that covers the statistical basis of multiple regression.  We assume that you have had at least one statistics course covering regression analysis and that you have a regression book that you can use as a reference (see the Regression With Stata page and our Statistics Books for Loan page for recommended regression analysis books). This book is designed to apply your knowledge of regression, combine it with instruction on Stata, to perform, understand and interpret regression analyses. 

This first chapter will cover topics in simple and multiple regression, as well as the supporting tasks that are important in preparing to analyze your data, e.g., data checking, getting familiar with your data file, and examining the distribution of your variables.  We will illustrate the basics of simple and multiple regression and demonstrate the importance of inspecting, checking and verifying your data before accepting the results of your analysis. In general, we hope to show that the results of your regression analysis can be misleading without further probing of your data, which could reveal relationships that a casual analysis could overlook. 

In this chapter, and in subsequent chapters, we will be using a data file that was created by randomly sampling 400 elementary schools from the California Department of Education's API 2000 dataset.  This data file contains a measure of school academic performance as well as other attributes of the elementary schools, such as, class size, enrollment, poverty, etc.

You can access this data file over the web from within Stata with the Stata use command as shown below.   Note: Do not type the leading dot in the command -- the dot is a convention to indicate that the statement is a Stata command.

Once you have read the file, you probably want to store a copy of it on your computer (so you don't need to read it over the web every time).  Let's say you are using Windows and want to store the file in a folder called c:\regstata (you can choose a different name if you like). First, you can make this folder within Stata using the mkdir command.

We can then change to that directory using the cd command.

And then if you save the file it will be saved in the c:\regstata folder. Let's save the file as elemapi .

Now the data file is saved as c:\regstata\elemapi.dta and you could quit Stata and the data file would still be there.  When you wish to use the file in the future, you would just use the cd command to change to the c:\regstata directory (or whatever you called it) and then use the elemapi file.

1.1 A First Regression Analysis

Let's dive right in and perform a regression analysis using the variables api00, acs_k3, meals and full. These measure the academic performance of the school (api00), the average class size in kindergarten through 3rd grade (acs_k3), the percentage of students receiving free meals (meals) - which is an indicator of poverty, and the percentage of teachers who have full teaching credentials (full). We expect that better academic performance would be associated with lower class size, fewer students receiving free meals, and a higher percentage of teachers having full teaching credentials.   Below, we show the Stata command for testing this regression model followed by the Stata output.

Let's focus on the three predictors, whether they are statistically significant and, if so, the direction of the relationship. The average class size (acs_k3, b=-2.68), is not statistically significant at the 0.05 level (p=0.055), but only just so. The coefficient is negative which would indicate that larger class size is related to lower academic performance -- which is what we would expect.   Next, the effect of meals (b=-3.70, p=.000) is significant and its coefficient is negative indicating that the greater the proportion students receiving free meals, the lower the academic performance.  Please note, that we are not saying that free meals are causing lower academic performance.  The meals variable is highly related to income level and functions more as a proxy for poverty. Thus, higher levels of poverty are associated with lower academic performance. This result also makes sense.  Finally, the percentage of teachers with full credentials (full, b=0.11, p=.232) seems to be unrelated to academic performance. This would seem to indicate that the percentage of teachers with full credentials is not an important factor in predicting academic performance -- this result was somewhat unexpected.

Should we take these results and write them up for publication?  From these results, we would conclude that lower class sizes are related to higher performance, that fewer students receiving free meals is associated with higher performance, and that the percentage of teachers with full credentials was not related to academic performance in the schools.  Before we write this up for publication, we should do a number of checks to make sure we can firmly stand behind these results.  We start by getting more familiar with the data file, doing preliminary data checking, looking for errors in the data. 

1.2 Examining data

First, let's use the describe command to learn more about this data file.  We can verify how many observations it has and see the names of the variables it contains. To do this, we simply type 

We will not go into all of the details of this output.  Note that there are 400 observations and 21 variables.  We have variables about academic performance in 2000 and 1999 and the change in performance, api00, api99 and growth respectively. We also have various characteristics of the schools, e.g., class size, parents education, percent of teachers with full and emergency credentials, and number of students.  Note that when we did our original regression analysis it said that there were 313 observations, but the describe command indicates that we have 400 observations in the data file.

If you want to learn more about the data file, you could list all or some of the observations.  For example, below we list the first five observations.

This takes up lots of space on the page, but does not give us a lot of information.  Listing our data can be very helpful, but it is more helpful if you list just the variables you are interested in.  Let's list the first 10 observations for the variables that we looked at in our first regression analysis.

We see that among the first 10 observations, we have four missing values for meals.  It is likely that the missing data for meals had something to do with the fact that the number of observations in our first regression analysis was 313 and not 400.

Another useful tool for learning about your variables is the codebook command.  Let's do codebook for the variables we included in the regression analysis, as well as the variable yr_rnd.  We have interspersed some comments on this output in [square brackets and in bold].

The codebook command has uncovered a number of peculiarities worthy of further examination. Let's use the summarize command to learn more about these variables.  As shown below, the summarize command also reveals the large number of missing values for meals (400 - 315 = 85) and we see the unusual minimum for acs_k3 of -21.

Let's get a more detailed summary for acs_k3.  In Stata, the comma after the variable list indicates that options follow, in this case, the option is detail. As you can see below, the detail option gives you the percentiles, the four largest and smallest values, measures of central tendency and variance, etc. Note that summarize, and other commands, can be abbreviated: we could have typed sum acs_k3, d.

It seems as though some of the class sizes somehow became negative, as though a negative sign was incorrectly typed in front of them.   Let's do a tabulate of class size to see if this seems plausible.

Indeed, it seems that some of the class sizes somehow got negative signs put in front of them.  Let's look at the school and district number for these observations to see if they come from the same district.   Indeed, they all come from district 140.

Let's look at all of the observations for district 140.

All of the observations from district 140 seem to have this problem.  When you find such a problem, you want to go back to the original source of the data to verify the values. We have to reveal that we fabricated this error for illustration purposes, and that the actual data had no such problem. Let's pretend that we checked with district 140 and there was a problem with the data there, a hyphen was accidentally put in front of the class sizes making them negative.  We will make a note to fix this!  Let's continue checking our data.

Let's take a look at some graphical methods for inspecting data.  For each variable, it is useful to inspect them using a histogram, boxplot, and stem-and-leaf plot.  These graphs can show you information about the shape of your variables better than simple numeric statistics can. We already know about the problem with acs_k3, but let's see how these graphical methods would have revealed the problem with this variable.

First, we show a histogram for acs_k3. This shows us the observations where the average class size is negative.

Likewise, a boxplot would have called these observations to our attention as well.   You can see the outlying negative observations way at the bottom of the boxplot.

Finally, a stem-and-leaf plot would also have helped to identify these observations.   This plot shows the exact values of the observations, indicating that there were three -21s, two -20s, and one -19. 

We recommend plotting all of these graphs for the variables you will be analyzing. We will omit, due to space considerations, showing these graphs for all of the variables. However, in examining the variables, the stem-and-leaf plot for full seemed rather unusual.  Up to now, we have not seen anything problematic with this variable, but look at the stem and leaf plot for full below. It shows 104 observations where the percent with a full credential is less than one.  This is over 25% of the schools, and seems very unusual.

Let's look at the frequency distribution of full to see if we can understand this better.  The values go from 0.42 to 1.0, then jump to 37 and go up from there.   It appears as though some of the percentages are actually entered as proportions, e.g., 0.42 was entered instead of 42 or 0.96 which really should have been 96.

Let's see which district(s) these data came from. 

We note that all 104 observations in which full was less than or equal to one came from district 401.  Let's count how many observations there are in district 401 using the count command and we see district 401 has 104 observations. 

All of the observations from this district seem to be recorded as proportions instead of percentages.  Again, let us state that this is a pretend problem that we inserted into the data for illustration purposes.  If this were a real life problem, we would check with the source of the data and verify the problem.  We will make a note to fix this problem in the data as well.

Another useful graphical technique for screening your data is a scatterplot matrix. While this is probably more relevant as a diagnostic tool searching for non-linearities and outliers in your data, it can also be a useful data screening tool, possibly revealing information in the joint distributions of your variables that would not be apparent from examining univariate distributions.  Let's look at the scatterplot matrix for the variables in our regression model.  This reveals the problems we have already identified, i.e., the negative class sizes and the percent full credential being entered as proportions. 

We have identified three problems in our data.  There are numerous missing values for meals, there were negatives accidentally inserted before some of the class sizes (acs_k3) and over a quarter of the values for full were proportions instead of percentages.  The corrected version of the data is called elemapi2.  Let's use that data file and repeat our analysis and see if the results are the same as our original analysis. First, let's repeat our original regression analysis below.

Now, let's use the corrected data file and repeat the regression analysis.  We see quite a difference in the results!  In the original analysis (above), acs_k3 was nearly significant, but in the corrected analysis (below) the results show this variable to be not significant, perhaps due to the cases where class size was given a negative value.  Likewise, the percentage of teachers with full credentials was not significant in the original analysis, but is significant in the corrected analysis, perhaps due to the cases where the value was given as the proportion with full credentials instead of the percent.   Also, note that the corrected analysis is based on 398 observations instead of 313 observations, due to getting the complete data for the meals variable which had lots of missing values.

From this point forward, we will use the corrected, elemapi2, data file.  You might want to save this on your computer so you can use it in future analyses.

So far we have covered some topics in data checking/verification, but we have not really discussed regression analysis itself.  Let's now talk more about performing regression analysis in Stata.

1.3 Simple Linear Regression

Let's begin by showing some examples of simple linear regression using Stata. In this type of regression, we have only one predictor variable. This variable may be continuous, meaning that it may assume all values within a range, for example, age or height, or it may be dichotomous, meaning that the variable may assume only one of two values, for example, 0 or 1. The use of categorical variables with more than two levels will be covered in Chapter 3. There is only one response or dependent variable, and it is continuous.

In Stata, the dependent variable is listed immediately after the regress command followed by one or more predictor variables. Let's examine the relationship between the size of school and academic performance to see if the size of the school is related to academic performance.  For this example, api00 is the dependent variable and enroll is the predictor.

Let's review this output a bit more carefully. First, we see that the F-test is statistically significant, which means that the model is statistically significant. The R-squared of .1012 means that approximately 10% of the variance of api00 is accounted for by the model, in this case, enroll. The t-test for enroll equals -6.70, and is statistically significant, meaning that the regression coefficient for enroll is significantly different from zero. Note that (-6.70)2 = 44.89, which is the same as the F-statistic (with some rounding error). The coefficient for enroll is -.1998674, or approximately -.2, meaning that for a one unit increase in enroll, we would expect a .2-unit decrease in api00. In other words, a school with 1100 students would be expected to have an api score 20 units lower than a school with 1000 students.  The constant is 744.2514, and this is the predicted value when enroll equals zero.  In most cases, the constant is not very interesting.  We have prepared an annotated output which shows the output from this regression along with an explanation of each of the items in it.

In addition to getting the regression table, it can be useful to see a scatterplot of the predicted and outcome variables with the regression line plotted.  After you run a regression, you can create a variable that contains the predicted values using the predict command.  You can get these values at any point after you run a regress command, but remember that once you run a new regression, the predicted values will be based on the most recent regression. To create predicted values you just type predict and the name of a new variable Stata will give you the fitted values. For this example, our new variable name will be fv, so we will type

If we use the list command, we see that a fitted value has been generated for each observation.

Below we can show a scatterplot of the outcome variable, api00 and the predictor, enroll.

We can combine scatter with lfit to show a scatterplot with fitted values. 

As you see, some of  the points appear to be outliers.  If you use the mlabel(snum) option on the scatter command, you can see the school number for each point.  This allows us to see, for example, that one of the outliers is school 2910.

As we saw earlier, the predict command can be used to generate predicted (fitted) values after running regress.  You can also obtain residuals by using the predict command followed by a variable name, in this case e, with the residual option.

This command can be shortened to predict e, resid or even predict e, r. The table below shows some of the other values can that be created with the predict option.

Value to be created                                    Option after Predict
---------------------------------------------------    --------------------
predicted values of y (y is the dependent variable)    no option needed 
residuals                                              resid
standardized residuals                                 rstandard 
studentized or jackknifed residuals                    rstudent 
leverage                                               lev or hat 
standard error of the residual                         stdr 
Cook's D                                               cooksd 
standard error of predicted individual y               stdf 
standard error of predicted mean y                     stdp 

1.4 Multiple Regression

Now, let's look at an example of multiple regression, in which we have one outcome (dependent) variable and multiple predictors. Before we begin with our next example, we need to make a decision regarding the variables that we have created, because we will be creating similar variables with our multiple regression, and we don't want to get the variables confused. For example, in the simple regression we created a variable fv for our predicted (fitted) values and e for the residuals.  If we want to create predicted values for our next example we could call the predicted value something else, e.g., fv_mr, but this could start getting confusing. We could drop the variables we have created, using drop fv e.  Instead, let's clear out the data in memory and use the elemapi2 data file again. When we start new examples in future chapters, we will clear out the existing data file and use the file again to start fresh.  

For this multiple regression example, we will regress the dependent variable, api00, on all of the predictor variables in the data set.

Let's examine the output from this regression analysis.  As with the simple regression, we look to the p-value of the F-test to see if the overall model is significant. With a p-value of zero to four decimal places, the model is statistically significant. The R-squared is 0.8446, meaning that approximately 84% of the variability of api00 is accounted for by the variables in the model. In this case, the adjusted R-squared indicates that about 84% of the variability of api00 is accounted for by the model, even after taking into account the number of predictor variables in the model. The coefficients for each of the variables indicates the amount of change one could expect in api00 given a one-unit change in the value of that variable, given that all other variables in the model are held constant. For example, consider the variable ell.   We would expect a decrease of 0.86 in the api00 score for every one unit increase in ell, assuming that all other variables in the model are held constant.  The interpretation of much of the output from the multiple regression is the same as it was for the simple regression.  We have prepared an annotated output that more thoroughly explains the output of this multiple regression analysis.

You may be wondering what a 0.86 change in ell really means, and how you might compare the strength of that coefficient to the coefficient for another variable, say meals. To address this problem, we can add an option to the regress command called beta, which will give us the standardized regression coefficients. The beta coefficients are used by some researchers to compare the relative strength of the various predictors within the model. Because the beta coefficients are all measured in standard deviations, instead of the units of the variables, they can be compared to one another. In other words, the beta coefficients are the coefficients that you would obtain if the outcome and predictor variables were all transformed standard scores, also called z-scores, before running the regression.

Because the coefficients in the Beta column are all in the same standardized units you can compare these coefficients to assess the relative strength of each of the predictors.  In this example, meals has the largest Beta coefficient, -0.66 (in absolute value), and acs_k3 has the smallest Beta, 0.013.  Thus, a one standard deviation increase in meals leads to a 0.66 standard deviation decrease in predicted api00, with the other variables held constant. And, a one standard deviation increase in acs_k3, in turn, leads to a 0.013 standard deviation increase in predicted api00 with the other variables in the model held constant.

In interpreting this output, remember that the difference between the numbers listed in the Coef. column and the Beta column is in the units of measurement.  For example, to describe the raw coefficient for ell you would say  "A one-unit decrease in ell would yield a .86-unit increase in the predicted api00." However, for the standardized coefficient (Beta) you would say, "A one standard deviation decrease in ell would yield a .15 standard deviation increase in the predicted api00."

The listcoef command gives more extensive output regarding standardized coefficients. It is not part of Stata, but you can download it over the internet like this.

and then follow the instructions (see also How can I use the findit command to search for programs and get additional help? for more information about using findit).  Now that we have downloaded listcoef, we can run it like this.

Let us compare the regress output with the listcoef output. You will notice that the values listed in the Coef., t, and P>|t| values are the same in the two outputs. The values listed in the Beta column of the regress output are the same as the values in the bStadXY column of listcoef. The bStdX column gives the unit change in Y expected with a one standard deviation change in X. The bStdY column gives the standard deviation change in Y expected with a one unit change in X. The SDofX column gives that standard deviation of each predictor variable in the model.

For example, the bStdX for ell is -21.3, meaning that a one standard deviation increase in ell would lead to an expected 21.3 unit decrease in api00.  The bStdY value for ell of -0.0060 means that for a one unit, one percent, increase in english language learners, we would expect a 0.006 standard deviation decrease in api00.  Because the bStdX values are in standard units for the predictor variables, you can use these coefficients to compare the relative strength of the predictors like you would compare Beta coefficients.  The difference is BStdX coefficients are interpreted as changes in the units of the outcome variable instead of in standardized units of the outcome variable.  For example, the BStdX for meals versus ell is -94 versus -21, or about 4 times as large, the same ratio as the ratio of the Beta coefficients.  We have created an annotated output that more thoroughly explains the output from listcoef.

So far, we have concerned ourselves with testing a single variable at a time, for example looking at the coefficient for ell and determining if that is significant. We can also test sets of variables, using the test command, to see if the set of variables are significant.  First, let's start by testing a single variable, ell, using the test command.

If you compare this output with the output from the last regression you can see that the result of the F-test, 16.67, is the same as the square of the result of the t-test in the regression (-4.083^2 = 16.67). Note that you could get the same results if you typed the following since Stata defaults to comparing the term(s) listed to 0.

Perhaps a more interesting test would be to see if the contribution of class size is significant.  Since the information regarding class size is contained in two variables, acs_k3 and acs_46, we include both of these with the test command.

The significant F-test, 3.95, means that the collective contribution of these two variables is significant.  One way to think of this, is that there is a significant difference between a model with acs_k3 and acs_46 as compared to a model without them, i.e., there is a significant difference between the "full" model and the "reduced" models.

Finally, as part of doing a multiple regression analysis you might be interested in seeing the correlations among the variables in the regression model.  You can do this with the correlate command as shown below.

If we look at the correlations with api00, we see meals and ell have the two strongest correlations with api00. These correlations are negative, meaning that as the value of one variable goes down, the value of the other variable tends to go up. Knowing that these variables are strongly associated with api00, we might predict that they would be statistically significant predictor variables in the regression model.

We can also use the pwcorr command to do pairwise correlations. The most important difference between correlate and pwcorr is the way in which missing data is handled. With correlate, an observation or case is dropped if any variable has a missing value, in other words, correlate uses listwise , also called casewise, deletion. pwcorr uses pairwise deletion, meaning that the observation is dropped only if there is a missing value for the pair of variables being correlated. Two options that you can use with pwcorr, but not with correlate, are the sig option, which will give the significance levels for the correlations and the obs option, which will give the number of observations used in the correlation. Such an option is not necessary with corr as Stata lists the number of observations at the top of the output.

1.5 Transforming Variables

Earlier we focused on screening your data for potential errors.  In the next chapter, we will focus on regression diagnostics to verify whether your data meet the assumptions of linear regression.  Here, we will focus on the issue of normality.  Some researchers believe that linear regression requires that the outcome (dependent) and predictor variables be normally distributed. We need to clarify this issue. In actuality, it is the residuals that need to be normally distributed.  In fact, the residuals need to be normal only for the t-tests to be valid. The estimation of the regression coefficients do not require normally distributed residuals. As we are interested in having valid t-tests, we will investigate issues concerning normality.

A common cause of non-normally distributed residuals is non-normally distributed outcome and/or predictor variables.  So, let us explore the distribution of our variables and how we might transform them to a more normal shape.  Let's start by making a histogram of the variable enroll, which we looked at earlier in the simple regression.

We can use the normal option to superimpose a normal curve on this graph and the bin(20) option to use 20 bins.  The distribution looks skewed to the right.

You may also want to modify labels of the axes. For example, we use the xlabel() option for labeling the x-axis below, labeling it from 0 to 1600 incrementing by 100.

Histograms are sensitive to the number of bins or columns that are used in the display. An alternative to histograms is the kernel density plot, which approximates the probability density of the variable. Kernel density plots have the advantage of being smooth and of being independent of the choice of origin, unlike histograms. Stata implements kernel density plots with the kdensity command.

Not surprisingly, the kdensity plot also indicates that the variable enroll does not look normal.  Now let's make a boxplot for enroll, using graph box command.

Note the dots at the top of the boxplot which indicate possible outliers, that is, these data points are more than 1.5*(interquartile range) above the 75th percentile. This boxplot also confirms that enroll is skewed to the right.

There are three other types of graphs that are often used to examine the distribution of variables; symmetry plots, normal quantile plots and normal probability plots.

A symmetry plot graphs the distance above the median for the i-th value against the distance below the median for the i-th value. A variable that is symmetric would have points that lie on the diagonal line.  As we would expect, this distribution is not symmetric.

A normal quantile plot graphs the quantiles of a variable against the quantiles of a normal (Gaussian) distribution. qnorm is sensitive to non-normality near the tails, and indeed we see considerable deviations from normal, the diagonal line, in the tails. This plot is typical of variables that are strongly skewed to the right.

Finally, the normal probability plot is also useful for examining the distribution of variables.  pnorm  is sensitive to deviations from normality nearer to the center of the distribution. Again, we see indications of non-normality in enroll.

Having concluded that enroll is not normally distributed, how should we address this problem?  First, we may try entering the variable as-is into the regression, but if we see problems, which we likely would, then we may try to transform enroll to make it more normally distributed.  Potential transformations include taking the log, the square root or raising the variable to a power. Selecting the appropriate transformation is somewhat of an art. Stata includes the ladder and gladder commands to help in the process. Ladder reports numeric results and gladder produces a graphic display. Let's start with ladder and look for the transformation with the smallest chi-square.

The log transform has the smallest chi-square. Let's verify these results graphically using gladder.

This also indicates that the log transformation would help to make enroll more normally distributed.  Let's use the generate command with the log function to create the variable lenroll which will be the log of enroll. Note that log in Stata will give you the natural log, not log base 10. To get log base 10, type log10(var).

Now let's graph our new variable and see if we have normalized it.

We can see that lenroll looks quite normal.  We would then use the symplot, qnorm and pnorm commands to help us assess whether lenroll seems normal, as well as seeing how lenroll impacts the residuals, which is really the important consideration.

1.6 Summary

In this lecture we have discussed the basics of how to perform simple and multiple regressions, the basics of interpreting output, as well as some related commands. We examined some tools and techniques for screening for bad data and the consequences such data can have on your results.  Finally, we touched on the assumptions of linear regression and illustrated how you can check the normality of your variables and how you can transform your variables to achieve normality.  The next chapter will pick up where this chapter has left off, going into a more thorough discussion of the assumptions of linear regression and how you can use Stata to assess these assumptions for your data.   In particular, the next lecture will address the following issues.

See the Stata Topics: Regression page for more information and resources on simple and multiple regression in Stata.

1.7 Self Assessment

  1. Make five graphs of api99: histogram, kdensity plot, boxplot, symmetry plot and normal quantile plot.
  2. What is the correlation between api99 and meals
  3. Regress api99 on meals. What does the output tell you?
  4. Create and list the fitted (predicted) values.
  5. Graph meals and api99 with and without the regression line.
  6. Look at the correlations among the variables api99 meals ell avg_ed using the corr and pwcorr commands. Explain how these commands are different. Make a scatterplot matrix for these variables and relate the correlation results to the scatterplot matrix.
  7. Perform a regression predicting api99 from meals and ell. Interpret the output.

Click here for our answers to these self assessment questions.

1.8 For More Information

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.