Docsity

informatica r funazionale cap 2, Dispense di Informatica

Anteprima parziale del testo

Scarica informatica r funazionale cap 2 e più Dispense in PDF di Informatica solo su Docsity!

CHAPTER 2 The Simple Linear Regression Model CHAPTER OUTLINE 2.1 The food expenditure data 2.5 Using Stata to obtain predicted values 2.1.1 Starting a new problem 2.5.1 Saving the Stata data file 2.1.2 Starting a log file 2.6 Estimating nonlinear relationships 2.1.3 Opening a Stata data file 2.6.1 A quadratic model 2.1.4 Browsing and listing the data 2.6.2 A log-linear model 2.2 Computing summary statistics 2.7 Regression with indicator variables 2.3 Creating a scatter diagram Appendix 2A Average marginal effects 2.3.1 Enhancing the plot 2A.1 Elasticity in a linear relationship 2.4 Regression 2A.2 Elasticity in a quadratic relationship 2.4.1 Fitted values and residuals 2A.3 Slope in a log-linear model 2.4.2 Computing an elasticity Appendix 2B A simulation experiment 2.4.3 Plotting the fitted regression line Key Terms 2.4.4 Estimating the variance of the error term Chapter 2 Do-file 2.4.5 Viewing estimated variances and covariance 2.1 THE FOOD EXPENDITURE DATA An example that recurs in the first few chapters of Principles of Econometrics, 4% edition (abbreviated as POE4) is an economic model of the relationship between weekly household food expenditure and weekly household income. First, start Stata and change the working directory. How this is done depends on your computer hardware and operating system. In this Windows-based book we use the working directory c:\data\poe4stata, and to change the working directory type cd c:\data\poe4stata 53 54 Chapter 2 on the command line and press Enter. Or follow the path File > Change Working Directory on the Stata pull-down menu. 2.1.1 Starting a new problem If you are beginning a new problem you must start by closing any log file that is open and clearing any data from memory. To Begin or Close a Stata log file click on the toolbar icon. If you have a log file open, a dialog box will appear giving you some options. Before beginning a new log file you must close the old one. Or, in the Command window enter log close To clear Stata's memory enter clear 2.1.2 Starting a log file To Begin or Close a Stata log file click on the toolbar icon, or enter the command log using chap02, replace text This will open the log file in a text format in the current directory. The option replace will cause any previous version of chap02.log to be written over, and erased. Remark: Users should open a log file for each chapter, or part of a chapter. We will remind you to Begin and Close log files in the early chapters, but will not thereafter. Make it a habit to use log files. 2.1.3 Opening a Stata data file The data for the food expenditure example is in the Stata data file food.dta and the definition file is food.def. To open the Stata data file click on Open (use) on the toolbar Locate food.dta, select it, and click Open. In the Command window, to open the data file in the current directory, enter 56 Chapter 2 Fie Edit Data Too dia aosrsig food_exp[1] Lisa i | food_exp ‘income si HE 135.98 4.39 dl 30 nos 4.75 Si 114.96 6.03 5 187.05 12.47 x ‘ all Re_Vars: 2 Obs: 40 Fiter: Off Mode:Browse (NUM | Close the Data Browser by clicking the “x” If you wish to “print” or list some of the data lines, on the pull-down menu click Data > Describe data > List data Describe data in memory I Data Editor »| Describe data in fe | Createorchangedata > Describe data contents (codebook) | Vatiables Manager Inspect variables Data us - ST ERO In the dialog box that opens simply click OK to list all the data to the Results window. The Stata command is list. The syntax of the list command is list [varlist] [if] [in] [, options] To list the values of specific variables, enter the variable names. The range of values to be listed can be modified using the logical “if” or “in” to denote specific lines. For example list in 1/5 list food_exp in 1/5 list food_exp if income <= 10 The Results window shows The Simple Linear Regression Model 57 . list in 1/5 food_exp income 115.22 3.69 135.98 4.39 119.34 4.75 114.96 6.03 187.05 12.47 UBWNH . list food_exp in 1/5 food_exp 115.22 135.98 119.34 114.96 187.05 UBAWNE . list food_exp if income <= 10 food_exp 115.22 135.98 119.34 114.96 AWUNH If the Results window fills, you may find more at the bottom. This indicates a pause. Either click —more- or press the space bar. The Stata command set more off will turn off the pause feature. 2.2 COMPUTING SUMMARY STATISTICS Now, check to determine if the data have the same summary statistic values as reported in the definition file. Using the pull-down menu, click on Statistics > Summaries, tables, and tests > Summary and descriptive statistics > Summary statistics In the resulting dialog box simply click OK for summary statistics on all the variables in the data set. You can also enter into the command line db summarize or db su to open the dialog box. The Command window equivalent is to enter summarize The syntax of the summarize command is summarize [varlist] [if] [in] [weight] [, options] The Simple Linear Regression Model 59 In the dialog box click Create [BI twoway - TWoway graphs. Piois |itin |vaxs]xaxs | Tiles | Legend] Overal| By | Plot definitions: rar Create]\ In the resulting dialog box choose Basic plots, Scatter then choose the Y variable (vertical axis) and the X variable (horizontal axis) using the pull-down arrows. Plot. |ifin | Plot number Yvanable variable: Ode 2] focome 2] ) Sontonavarisbie Marker propanies | Markerweighs __|Acceptthe type of plot peri for enhancements graph L CK [_Acp_]_ conce | swma | If you click Submit the scatter diagram will be created. The Stata command is twoway (scatter food_exp income) If you select Accept Plot 1 will appear in the Plot definitions window and the graph will be created when you click OK. To save the graph to disk to the default directory with the Stata graph extension *.gph use graph save foodl, replace Graphing and saving to disk can be accomplished in one-step using the saving option twoway (scatter food_exp income), saving(foodl, replace) 60 Chapter 2 Instead of saving to disk, you can save to memory using the name option. This may be handy if you are in a lab environment twoway (scatter food_exp income), name(foodl, replace) 2.3.1 Enhancing the plot To enhance the plot, in the Plot 1 dialog box, click Accept. In the Graphics dialog box this creates a Plot definition, or profile, called Plot 1. ea | | Click the tab Y axis. In the resulting dialog box select Major sck/label properties There are several options, but let us specify the range of the vertical axis. I Axis tick and label properties (y ts) (major tek) Rule |Labels| Ticke | Grid | (Use default rule ( Suggest officks | Minimumalue d fcoo Maximum value. (Min Max È _ Too Delta ‘o specify vertical i ( None i The axis rule determines the number ofticks and therr relative positions Increment between major ticks CE) (ese ] sn] Click the Range/Delta option. From the data summary statistics we know the minimum and maximum values of food_exp. So that we can view the entire range of data select Minimum value 0 and Maximum value 600. Delta is the units of measure for the axis—the space between tick marks. Set this value to 100. Click Accept. Repeat this process for the X axis, using as Maximum value 35 and a Delta of 5. Click Accept 62 Chapter 2 content is ignored by Stata. For discussion of alternative comment commands enter help comments. twoway (scatter food_exp income), is the same command used to produce the simple scatter. The comma is important, and indicates options that will be applied. ylabe1(0(100)600) specifies the range of the Y axis, 0 to 600, and space between the major ticks, 100. xlabe](0(5)35) specifies the range, 0 to 35, and increment for the X axis, 5. title(Food Expenditure Data) specifies the primary title. Once again you can add the saving option to the twoway command, or use the option name to save to memory, or use a graph save command. We use graph save commands in the do-file for this chapter. 2.4 REGRESSION The simple linear regression model is y=B+Bx+e Given data on the dependent variable, y (food_exp), and the independent variable, x (income), we can use Stata to estimate the unknown parameters. Regression analysis uses the pull-down menu from Statistics > Linear models and related > Linear regression In the Regress - Linear regression dialog box select the dependent variable to be food_exp. This is the left-hand side variable in the regression model. Select (or enter) income as the independent (right-hand side) variable. Stata will automatically include an intercept term in the estimation. Click OK. [BH regress - Linear regressioni | Pl tal £3| Mode! | by/ifin | Weights | SE/Robust| Reporting | Dependeni variable Independent vaniables ten si_] [rome zio Alternatively the command line syntax is The Simple Linear Regression Model 63 regress depvar [indepvars] [if] [in] [weight] [, options] See help regress. This shows that the dependent variable depvar is listed first and then the independent variable or variables (for a multiple regression), indepvars. You can use if or in to limit the sample, assign weights to the observations or use options, if desired. We discuss these options more in future chapters. For the food expenditure the simple regression command is regress food_exp income which can be shortened to reg food_exp income In the Results window the Stata command for the regression is given, and a display of regression results. We will explore all of these items, but for now focus on the first two columns labeled food_exp and Coef. The first column gives the variable names. Remember that computer software will not know that you call the estimates “b1” and “b2” and will instead list these with variable names. Stata lists the slope coefficient first, income. The y-intercept is labeled _cons, short for “constant” or “constant term,” which is another common name for the y-intercept. regress food_exp income Source ss df MS Number of obs = 40 EC 1 38) = 23.79 Mode] 190626 .984 1 190626.984 Prob > F = 0.0000 Residual 304505.176 38 8013.2941 R-squared = 0.3850 Adj R-squared = 0.3688 Total 495132.16 39 12695.6964 Root MSE = 89.517 food_exp coef. Std. Err. i P>|tl [95% conf. Interval] income 10.20964 —2.093264 4.88 0.000 5.972052 14.44723 cons 83.416 43.41016 1.92 0.062 -4.463279 171.2953 2.4.1 Fitted values and residuals The fitted, or predicted, values Î are obtained using what are called “postestimation” commands. They are called “postestimation” options because they follow the estimation of the regression model. After help regress the link to the postestimation options is in the upper right- hand corner. The Simple Linear Regression Model 65 These commands have created two new variables, yhat and ehat, which appear in the Variables window. Examine these values by selecting the Data Browser, or use the command Browse [RI Data Editor (&rowse) - [f00d] — =l9x He EGt Cata. Toe ida SL ag toos 0001) (e re ma foodexp income yhat chat 4 Qa[ 152] 3.69 121.0896 -5.869585 Za 119,34 4,75 131.918 -12.57181 4 114.96 6.03 144.9801 -30.02015 5 187.05 12.47 210.730 -23.68025 4 si Resdy Vari Cos: 0 File: 0# Mode:Bione (\ tum | The Stata commands that compute the fitted values and least squares residuals are obtained using the fundamental postestimation command predict. Close the browser and in the Command window type help predict The basic syntax for predict is predict [type] newvar [if] [in] [, single_options] What is required is the name of the variable, newvar, and an option. To obtain fitted values use the option xb which is short for “x times b”. predict yhat, xb Obtaining predictions are actually the default for this command, so we could have used predict yhat To obtain residuals use the option residuals. For the food expenditure model these are predict ehat, residuals 66 Chapter 2 The option residuals can be shortened to the minimum of r, or a bit longer like res or resid. 2.4.2 Computing an elasticity Given the parameter estimates, and the summary statistics for the variables, we can easily compute other quantities, like the elasticity of food expenditure with respect to income, evaluated at the means 19.60 _ 283.57 0.71 x One of Stata”s post-estimation commands allows computing this elasticity automatically. Select Statistics > Postestimation > Marginal effects. Predictona, resa, etc. Noninenr predcione Merginsi means andpredicive macgne In the resulting dialog box select the radio button for Elasticities and the Variable. In our simple regression model there is only one variable to select, income. To evaluate the elasticity at the sample means select the At tab, and click the radio button for AIl covariates at their means in the sample. ail Man |A _ | d4vover] Wehn | SE | Advanced | Reportng | Factor terms to mangino for si if no factorterms specfied È i At specific values [E © Sorefan eprasien al estimaed coronate i Choose variable i 3 TT Treat factor variable levelindicator covanates as continuous ii CICEI [dci |_som | 68 Chapter 2 Note only does Stata report the elasticity, but computes a standard error for this quantity and a confidence interval as well'. It shows the value of income at which this quantity is calculated, which is the sample mean. Most commonly the elasticity is calculated at the “point of the means” (x,7)=(19.60,283.57) because it is a representative point on the regression line. Remark: Computer software is dangerous to the learning process. You must not rely on pointing and clicking to obtain an answer without understanding what calculation is occurring, and how the quantity is interpreted. Neat computing tricks are not a substitute for really learning the material. Rather than computing the elasticity at one specific point we can alternatively find the elasticity at cach value of y and x and then average this quantity across all observations. This is called an Average marginal effect, in this case average elasticity. That is, compute AME=% Stata will compute The Stata margins command for this quantity omits the previously used “atmeans” option margins, eyex( income ) The results are? now Average marginal effects, rather than Conditional marginal effects as above. . margins, eyex( income ) Average marginal effects Number of obs = 40 Mode] VcE 1 OL Expression 1 Linear prediction, predict() ey/ex w.r.t. : income Delta-method ey/ex Std. Err. z P>Iz| [95% conf. Interval] income 6796126 +1466535 4.63 0.000 .3921769 +9670482 We can verify this calculation. After a regression Stata saves the estimated coefficients in its memory, though not indefinitely. Regression coefficients are designated _b[varname]. After the food expenditure regression, the estimated slope is stored as _b[income]. The elasticity calculation, evaluated for each observation in the sample, is then * The calculation of the standard error is discussed in an appendix to this chapter. ? More details of this calculation are given in an appendix to this chapter. The Simple Linear Regression Model 69 generate elas = _b[income]*income/yhat The average elasticity is summarize elas We have then in the Results window . generate elas = _b[income]*income/yhat . summarize elas Variable | Obs Mean Std. Dev. Min Max elas | 40 +6796126 +1168024 «3111216 .8034579 In these results the Std. Dev. reported is the sample standard deviation. The margins command produces something called a Delta-method Std. Err. These are not the same. The Delta method is introduced in Chapter 5 of POE4. 2.4.3 Plotting the fitted regression line To plot the fitted regression line use the pull-down menu Graphics > Twoway graph (scatter, line, etc.). If you are continuing this session and have done the scatter plot in Section 2.3 then Plot 1, the scatter diagram, already exists. We will create a new plot for the linear prediction. Click Create. In the Plot 2 dialog box, choose Fit plots and Linear prediction with Y variable and X variable as food_exp and income. T" Adda secondy ass oniott oa__| 20 (Ci ] ca |_som | Click on Accept. Change the title by clicking on Titles, enter a new title. Return to Plots tab. Clicking Submit will create the graph and leave the window open. The Simple Linear Regression Model 71 where è, = y, —D, = y, —b, —b,x; are the least squares residuals. The “2” in the denominator is the number of regression parameters, here B, and f,. In the Stata regression output this quantity is given in the Analysis of Variance table. Source ss df Ms Mode] 190626. 984 1 190626.984 Residual 304505.176 38 8013.2941 + Pi n Total 495132.16 39 12695.6964 sum of squared residuals —N:2 estimated variance of errorterm Focus on the row Residual. The column labeled SS contains Sums of Squares. The value 304505.176 is the sum of squared least squares residuals x SSE =Y è? = SS Residual The column labeled df is the (residual) degrees of freedom, which in this case is N — 2 = 38. The model degrees of freedom is 1, which is the number of parameters other than the intercept, here B,. The column header MS stands for Mean Square. The mean of the squared residuals is the estimated error variance 6° = = MS Residual = 8013.2941 N-2 The other components of the table will be explained later. 2.4.5 Viewing estimated variances and covariance After a regression is estimated there are many regression related statistics calculated but not reported by Stata. The estimated variances and covariance of the least squares estimators for the food expenditure model are (ci a = 1884.4423 72 Chapter 2 rit AVI xx) |tl [95% conf. Interval] income 10.20964 2.093264 4.88 0.000 5.972052 14.44723 cons 83.416 43.41016 1,92 0.062 -4.463279 171.2953