{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 14 - Good Regression Practices\n", "\n", "Marina Adshade, Paul Corcuera, Giulia Lo Forte, Jane Platt \n", "2024-05-29\n", "\n", "## Prerequisites\n", "\n", "1. Importing data into Stata.\n", "2. Creating new variables using `generate` and `replace`.\n", "3. Identifying percentiles in data using `summarize` and `return list`.\n", "4. Running OLS regressions.\n", "\n", "## Learning Outcomes\n", "\n", "1. Identify and correct for outliers by trimming or winsorizing the\n", " dependent variable.\n", "2. Identify and correct for the problem of multicollinearity.\n", "3. Identify and correct for the problem of heteroskedasticity.\n", "4. Identify and correct for the problem of non-linearity.\n", "\n", "## 14.1 Dealing with Outliers\n", "\n", "Imagine that we have constructed a dependent variable which contains the\n", "earnings growth of individual workers and we see that some worker’s\n", "earnings increased by more than 400%. We might wonder if this massive\n", "change is just a coding error made by the statisticians that produced\n", "the data set. Even without that type of error, though, we might worry\n", "that the earnings growth of a small number of observations are driving\n", "the results of our analysis. If this is the case, we will produce an\n", "inaccurate analysis based on results that are not associated with the\n", "majority of our observations.\n", "\n", "The standard practice in these cases is to either winsorize or trim the\n", "subset of observations that are used in that regression. Both practices\n", "remove the outlier values in the dependent variable to allow us to\n", "produce a more accurate empirical analysis. In this section, we will\n", "look at both approaches.\n", "\n", "**Warning:** We should only consider fixing outliers when there is a\n", "clear reason to address this issue. Do not apply the tools below if the\n", "summary statistics in your data make sense to you in terms of abnormal\n", "values. For example, outliers might be a sign that our dependent and\n", "explanatory variables have a non-linear relationship. If that is the\n", "case, we will want to consider including an interaction term that\n", "addresses that non-linearity. A good way to test for this is to create a\n", "scatter plot of our dependent and independent variables. This will help\n", "us to see if there are actually some outliers, or if there is just a\n", "non-linear relationship.\n", "\n", "### 14.1.1 Winsorizing a Dependent Variable\n", "\n", "Winsorizing is the process of limiting extreme values in the dependent\n", "variable to reduce the effect of (possibly erroneous) outliers. It\n", "consists of replacing values below the $a$th percentile by that\n", "percentile’s value, and values above the $b$th percentile by that\n", "percentile’s value. Consider the following example using our fake data\n", "set:\n", "\n", "``` {stata}\n", "clear all\n", "*cd \"\"\n", "use fake_data, clear \n", "```\n", "\n", "Let’s have a look at the distribution of earnings in the data set.\n", "\n", "Specifically, focus on the earnings at four points of the distribution:\n", "the minimum, the maximum, the 1st percentile, and the 99th percentile.\n", "We can display them using locals, as seen in [Module\n", "4](https://comet.arts.ubc.ca/docs/Research/econ490-stata/04_Locals_and_Globals.html).\n", "\n", "``` {stata}\n", "summarize earnings, detail\n", "local ratio_lb = round(r(p1)/r(min))\n", "local ratio_ub = round(r(max)/r(p99))\n", "display \"The earnings of the individual in the 1st percentile are `r(p1)'\"\n", "display \"The lowest earner in the dataset earned `r(min)'\"\n", "display \"The earnings of the individual in the 99th percentile are `r(p99)' \"\n", "display \"The highest earner in the dataset earned `r(max)'\"\n", "display \"The individual in the 1st pctile earned `ratio_lb' times as much as the lowest earner!\"\n", "display \"The highest earner earned `ratio_ub' times as much as the individual in the 99th pctile!\"\n", "```\n", "\n", "From the summary statistics above, we can see that that the income\n", "earned by the individual at the 1st percentile is 2,831.03 and that the\n", "lowest earner in the data set earned 8.88.\n", "\n", "We can also see that income earned by the individual at the 99th\n", "percentile is only 607,140.32 and that the highest earner in the data\n", "earned over 60 millions!\n", "\n", "These facts suggest to us that there are large outliers in our dependent\n", "variable.\n", "\n", "We want to get rid of these outliers by winsorizing our data set. What\n", "that means is replacing the earnings of all observations below the 1st\n", "percentile by exactly the earnings of the individual at the 1st\n", "percentile, and replacing the earnings of all observations above the\n", "99th percentile by exactly the earnings of the individual at the 99th\n", "percentile.\n", "\n", "Recall that we can see how Stata stored the information in the\n", "previously run `summarize` command by using the command `return list`.\n", "\n", "``` {stata}\n", "return list\n", "```\n", "\n", "To winsorize this data, we do the following 3 step process:\n", "\n", "1. We create a new variable called *earnings_winsor* which is identical\n", " to our *earnings* variable (`gen earnings_winsor = earnings`). We\n", " choose to store the winsorized version of the dependent variable in\n", " a different variable so that we don’t overwrite the original data\n", " set.\n", "2. If earnings are smaller than the 1st percentile, we replace the\n", " values of *earnings_winsor* with the earnings of the individual at\n", " the 1st percentile (stored in Stata in `r(p1)`). Note that we need\n", " to ensure that Stata does not replace missing values with `r(p1)`.\n", "3. If earnings are larger than the 99th percentile, we replace the\n", " values of *earnings_winsor* with the earnings of the individual at\n", " the 99th percentile (stored in Stata in `r(p99)`). Note that we need\n", " to ensure that Stata does not replace missing values with `r(p99)`.\n", "\n", "We do this below:\n", "\n", "``` {stata}\n", "generate earnings_winsor = earnings\n", "replace earnings_winsor = r(p1) if earnings_winsorr(p99) & earnings_winsor!=.\n", "```\n", "\n", "Let’s take a look at the summary statistics of the original earnings\n", "variable and the new variable that we have created:\n", "\n", "``` {stata}\n", "summarize earnings earnings_winsor\n", "```\n", "\n", "Now we will use this new dependent variable in our regression analysis.\n", "If the outliers were not creating problems, there will be no change in\n", "the results. If they were creating problems, those problems will now be\n", "fixed.\n", "\n", "Let’s take a look at this by first running the regression from [Module\n", "11](https://comet.arts.ubc.ca/docs/Research/econ490-stata/11_Linear_Reg.html)\n", "with the original *logearnings* variable.\n", "\n", "``` {stata}\n", "capture drop logearnings\n", "generate logearnings = log(earnings)\n", "regress logearnings age \n", "```\n", "\n", "Now we will run this again, using the new winsorized *logearnings*\n", "variable.\n", "\n", "``` {stata}\n", "capture drop logearnings_winsor\n", "generate logearnings_winsor = log(earnings_winsor)\n", "regress logearnings_winsor age \n", "```\n", "\n", "Do you think that in this case the outliers were having a significant\n", "impact before being winsorized?\n", "\n", "### 14.1.2 Trimming a Dependent Variable\n", "\n", "Trimming consists of replacing both values below the $a$th percentile\n", "and values above the $b$th percentile by a missing value. This is done\n", "to exclude these outliers from regression, since Stata automatically\n", "excludes missing observations in the command `regress`.\n", "\n", "Below, we look at the commands for trimming a variable. Notice that the\n", "steps are quite similar to when we winsorized the same variable. Don’t\n", "forget to create a new *earnings_trim* variable to avoid overwriting our\n", "original variable!\n", "\n", "``` {stata}\n", "summarize earnings, detail\n", "\n", "capture drop earnings_trim\n", "generate earnings_trim = earnings\n", "replace earnings_trim = . if earnings_trim < r(p1) & earnings_trim!=.\n", "replace earnings_trim = . if earnings_trim > r(p99) & earnings_trim!=.\n", "```\n", "\n", "And here is the result of the regression with the new dependent\n", "variable:\n", "\n", "``` {stata}\n", "capture drop logearnings_trim\n", "generate logearnings_trim = log(earnings_trim)\n", "regress logearnings_trim age \n", "```\n", "\n", "## 14.2 Multicollinearity\n", "\n", "If two variables are linear combinations of one another they are\n", "multicollinear. Ultimately, Stata does not allow us to include two\n", "variables in a regression that are perfect linear combinations of one\n", "another, such as a constant or a dummy variable for male and a dummy for\n", "female (since female = 1 - male). In all of the regressions above, we\n", "see that one of those variables was dropped from the regression “because\n", "of collinearity”.\n", "\n", "``` {stata}\n", "capture drop male\n", "generate male = sex == \"M\"\n", "\n", "capture drop female \n", "generate female = sex == \"F\"\n", "```\n", "\n", "``` {stata}\n", "regress logearnings male female\n", "```\n", "\n", "Is this a problem? Not really. Multicollinearity is a sign that a\n", "variable is not adding any new information. Notice that with the\n", "constant term and a male dummy we can know the mean earnings of females.\n", "In this case, the constant term is, by construction, the mean earnings\n", "of females, and the male dummy gives the earning premium paid to male\n", "workers.\n", "\n", "While there are some statistical tests for multicollinearity, nothing\n", "beats having the right intuition when running a regression. If there is\n", "an obvious case where two variables contain basically the same\n", "information, we’ll want to avoid including both in the analysis.\n", "\n", "For instance, we might have an age variable that includes both years and\n", "months (e.g. if a baby is 1 year and 1 month old, then this age variable\n", "would be coded as 1 + 1/12 = 1.083). If we included this variable in a\n", "regression which also included an age variable that includes only years\n", "(e.g the baby’s age would be coded as 1) then we would have the problem\n", "of multicollinearity. Because they are not perfectly collinear, Stata\n", "might still produce some results; however, the coefficients on these two\n", "variables would be biased.\n", "\n", "## 14.3 Heteroskedasticity\n", "\n", "When we run a linear regression, we essentially split the outcome into a\n", "(linear) part explained by observables ($x_i$) and an error term\n", "($e_i$): $$\n", "y_i = a + b x_i + e_i\n", "$$\n", "\n", "The standard errors in our coefficients depend on $e_i^2$ (as you might\n", "remember from your econometrics courses). Heteroskedasticity refers to\n", "the case where the variance of this projection error depends on the\n", "observables $x_i$. For instance, the variance of wages tends to be\n", "higher for people who are university educated (some of these people have\n", "very high wages) whereas it is small for people who are non-university\n", "educated (these people tend to be concentrated in lower paying jobs).\n", "Stata by default assumes that the variance does not depend on the\n", "observables, which is known as homoskedasticity. It is safe to say that\n", "this is an incredibly restrictive assumption.\n", "\n", "While there are tests for heteroskedasticity, the more empirical\n", "economists rely on including the option `robust` at the end of the\n", "`regress` command for the OLS regression to address this. This will\n", "adjust our standard errors to make them robust to heteroskedasticity.\n", "\n", "``` {stata}\n", "capture drop logearnings\n", "generate logearnings = log(earnings)\n", "regress logearnings age, robust\n", "```\n", "\n", "Best practices are simply to always use robust standard errors in your\n", "own research project, since most standard errors will be\n", "heteroskedastic.\n", "\n", "## 14.4 Non-linearity\n", "\n", "Our regression analysis so far assumes that the relationship between our\n", "independent and explanatory variables is linear. If this is not the\n", "case, and the relationship is non-linear, then we are getting inaccurate\n", "results with our analysis.\n", "\n", "Let’s consider an example. We know that earnings increases with age, but\n", "what if economic theory predicts that earnings increase by more for each\n", "year of age when workers are younger than when they are older? What we\n", "are asking here is whether earnings is increasing with age at a\n", "decreasing rate. In essence, we want to check whether there is a concave\n", "relation between age and earnings. We can think of several mechanisms\n", "for why this relationship might exist: for a young worker, as they age,\n", "they get higher wages through increased experience in the job; for an\n", "older worker, as they age, those wage increases will be smaller as there\n", "are smaller productity gains with each additional year working. In fact,\n", "if the productivity of workers decreaseas as they age, perhaps for\n", "reasons related to health, then it is possible to find a negative\n", "relationship between age and earning beyond a certain age – the\n", "relationship would be an inverted U-shape.\n", "\n", "We could check if this is the case in our model by including a new\n", "interaction term that is simply age interacted with itself, which is the\n", "equivalent of including age and age squared. We learned how to do this\n", "in [Module\n", "13](https://comet.arts.ubc.ca/docs/Research/econ490-stata/13_Dummy.html).\n", "Let’s include this in the regression above, remembering that age is a\n", "continuous variable (do you remember how to include a continuous\n", "variable in a regression?).\n", "\n", "``` {stata}\n", "regress logearnings c.age##c.age\n", "```\n", "\n", "There does seem to be some evidence in our regression results that this\n", "economic theory is correct, since the coefficient on the interaction\n", "term is both negative and statistically significant.\n", "\n", "How do we interpret these results? Let’s think about the equation we\n", "have just estimated: $$\n", "Earnings_i = \\beta_0 + \\beta_1 Age_i + \\beta_2 Age^2_i + \\varepsilon_i \n", "$$\n", "\n", "This means that earnings of an individual change in the following way\n", "with their age: $$\n", "\\frac{\\partial Earnings_i}{\\partial Age_i} = \\beta_1 + 2 \\beta_2 Age_i\n", "$$\n", "\n", "Due to the quadratic term, as age changes, the relationship between age\n", "and earnings changes as well.\n", "\n", "We have just estimated $\\beta_1$ to be positive and equal to 0.079, and\n", "$\\beta_2$ to be negative and equal to 0.001.\n", "\n", "This means that, as age increases, it’s correlation with earnings\n", "decrease: $$\n", "\\frac{\\partial Earnings_i}{\\partial Age_i} = 0.079 - 2 * 0.001 Age_i\n", "$$\n", "\n", "Since the marginal effect changes with the size of $Age_i$, providing\n", "one unique number for the marginal effect becomes difficult.\n", "\n", "The most frequently reported version of this effect is the “marginal\n", "effect at the means”: the marginal effect of age on earnings when age\n", "takes its average value. In our case, this will be equal to 0.079 minus\n", "0.002 times the average value of age.\n", "\n", "To do this in practice, we store the estimated coefficients and average\n", "age in three locals: local *agemean* stores the average age, while\n", "locals *beta1* and *beta2* store the estimated coefficients. We learned\n", "how to do this in [Module\n", "4](https://comet.arts.ubc.ca/docs/Research/econ490-stata/04_Locals_and_Globals.html).\n", "Notice that Stata automatically stores the estimated coefficients in\n", "locals with syntax `_b[regressor name]`. To retrieve the estimated\n", "coefficient $\\beta_2$, we manually create the variable $Age^2_i$ and\n", "call it *agesq*.\n", "\n", "``` {stata}\n", "summarize age\n", "local agemean : display %2.0fc r(mean)\n", "capture drop agesq\n", "generate agesq = age*age\n", "regress logearnings age agesq\n", "local beta1 : display %5.3fc _b[age]\n", "local beta2 : display %5.3fc _b[agesq]\n", "local marg_effect = `beta1' + (2 * `beta2' * `agemean')\n", "display \"beta1 is `beta1', beta2 is `beta2', and average age is `agemean'.\"\n", "display \"Therefore, the marginal effect at the means is `beta1' + 2*(`beta2')*`agemean', which is equal to `marg_effect'.\"\n", "```\n", "\n", "We find that the marginal effect at the mean is -0.011. What does that\n", "mean? It means that, for the average person, becoming one year older is\n", "associated with a 1% decrease in log earnings.\n", "\n", "Notice that this is the effect for the *average person*. Is the same\n", "true for young workers and older workers? To learn how to interpret this\n", "non-linearity in age, let’s see how the predicted earnings correlate\n", "with age.\n", "\n", "We can obtain the predicted earnings with the `predict` command and then\n", "use a scatterplot to eyeball it’s relationship with age. We covered how\n", "to create scatterplots in [Module\n", "9](https://comet.arts.ubc.ca/docs/Research/econ490-stata/09_Stata_Graphs.html)\n", "and the `predict` function in [Module\n", "11](https://comet.arts.ubc.ca/docs/Research/econ490-stata/11_Linear_Reg.html).\n", "\n", "**Note:** Stata graphs will not appear in the Jupyter Notebooks. To make\n", "the most out of this part of the module, it is recommended that you run\n", "this code on Stata installed locally in your computer.\n", "\n", "``` {stata}\n", "* Run the regression with the quadratic term\n", "regress logearnings c.age##c.age\n", "\n", "* Predict earnings and save them as yhat\n", "predict yhat, xb\n", "\n", "* Plot the scatterplot\n", "twoway scatter yhat age\n", "```\n", "\n", "The scatterplot shows an inverted-U relationship between age and the\n", "predicted log-earnings. This relationship implies that, when a worker is\n", "very young, aging is positively correlated with earnings. However, after\n", "a certain age, this correlation becomes negative and the worker gets\n", "lower earnings for each additional year of age. In fact, based on this\n", "graph, workers earnings start to decline just after the age of 50. Had\n", "we modelled this as a linear model, we would have missed this important\n", "piece of information!\n", "\n", "**Note:** If there is a theoretical reason for believing that\n", "non-linearity exists, Stata provides some tests for non-linearity. We\n", "can also create a scatter-plot to see if we observe a non-linear\n", "relationship in the data. We covered that approach in [Module\n", "9](https://comet.arts.ubc.ca/docs/Research/econ490-stata/9_Stata_Graphs.html).\n", "\n", "## 14.5 Wrap Up\n", "\n", "It is important to always follow best practices for regression analysis.\n", "Nonetheless, checking and correcting for outliers, as well as addressing\n", "heteroskedasticity, multicollinearity and non-linearity can be more of\n", "an art than a science. If you need any guidance on whether or not you\n", "need to address these issues, please be certain to speak with your\n", "instructor, TA, or supervisor.\n", "\n", "## References\n", "\n", "[How to identify and replace unusual data\n", "values](https://www.youtube.com/watch?v=jIiHb0gsyVo)" ], "id": "71f33779-8179-487c-82a4-558ebdf3224f" } ], "nbformat": 4, "nbformat_minor": 5, "metadata": { "kernelspec": { "name": "python3", "display_name": "Python 3 (ipykernel)", "language": "python", "path": "/usr/local/share/jupyter/kernels/python3" }, "language_info": { "name": "python", "codemirror_mode": { "name": "ipython", "version": "3" }, "file_extension": ".py", "mimetype": "text/x-python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.12" } } }