2 title: "Week 11 (ha) R tutorial"
4 date: "November 24, 2020"
21 ```{r setup, include=FALSE}
22 knitr::opts_chunk$set(echo = TRUE)
27 There is a whole lot we will not have a chance to cover in this course related to regression analysis and interpretation, but I wanted to write out a brief R tutorial on some topics that are just beyond the reach of the material introduced by our textbook and problem sets. If you have any interest/need to apply these kinds of techniques in your final projects, I hope these examples will help and give you a sense of where/how to direct your questions. As always, please get in touch when you run into trouble.
29 ## Import data for the examples
30 For all of the examples this week, I'll work with the `population.tsv` dataset from back in [Week 6](https://communitydata.science/~ads/teaching/2020/stats/data/week_06/). The following lines of code load it and clean it up a bit. Since we've worked with this dataset before I will not revisit the process of "getting to know" it.
33 ```{r Import and cleanup data}
34 d <- read.delim(url("https://communitydata.science/~ads/teaching/2020/stats/data/week_06/population.tsv"))
36 d$j <- as.logical(d$j)
37 d$l <- as.logical(d$l)
40 labels=c("some", "lots", "all"))
42 d <- d[complete.cases(d),]
47 It is often necessary to transform variables for modeling (we'll discuss some reasons why in class). Here are some common transformations with example code to perform them in R. Keep in mind that you also know some others (e.g., you know how to standardize a variable or take the square root).
51 Interaction terms are best handled using the `I()` function (note the capitalization). I start with a "base" model and update it to add the interaction.
54 m.base <- formula(y ~ x + j)
55 summary(lm(m.base, data=d))
58 m.i <- update.formula(m.base, . ~ . + I(x*j))
59 summary(lm(m.i, data=d))
62 ### Polynomial (square, cube, etc.) terms
64 Polynomial terms can easily be created using `I()` as well:
67 m.poly <- update.formula(m.base, . ~ . + I(x^2))
68 summary(lm(m.poly, data=d))
70 Need higher order polynomials? Try including `I(x^3)` and so on...
72 Creating polynomials this way is intuitive, but can also create a little bit of a messy situation for reasons that go beyond the scope of our course. In these circumstances, using the `poly()` function is useful (look up "orthogonalized polynomials" online to learn more). Generally speaking, creating polynomials in this way impacts the interpretation as well as the model estimates, so you should only use it if you need to and once you've taken the time to actually learn what is happening. That said, here's what the code could look like:
75 m.poly2 <- formula(y ~ j + poly(x,2))
76 summary(lm(m.poly2, data=d))
78 Higher order (to the nth degree) terms can be created by using higher values of `n` as an argument to (e.g. `poly(x, n)`).
80 ### Log-transformations
82 We covered log transformations (usually natural logarithms) before, but just in case, here they are again. I usually default to using `log1p()` because it is less prone ot fail in the event your data (like mine) contains many zeroes. That said, if you have a lot of -1 values you may need something else:
85 m.log <- update.formula(m.base, . ~ log1p(x) + j)
86 summary(lm(m.log, data=d))
88 Keep in mind that you can use other bases for your logarithmic transformations. Check out the documentation for `log()` for more information.
90 ## Interpreting regression results with model-predicted values
92 When you report the results of a regression model, you should provide a table summarizing the model as well as some interpretation that renders the model results back into the original, human-intelligible measures and units specific to the study.
94 This was covered in one of the [resources](https://communitydata.science/~mako/2017-COM521/logistic_regression_interpretation.html) I distributed last week (the handout on logistic regression from Mako Hill), but I wanted to bring it back because it is **important**. Please revisit that handout to see a worked example that walks through the process. The rest of this text is a bit of a rant about why you should bother to do so.
96 When is a regression table not enough? In textbook/homework examples, this is not an issue, but in real data it matters all the time. Recall that the coefficient estimated for any single predictor is the expected change in the outcome for a 1-unit change in the predictor *holding all the other predictors constant.* What value are those other predictors held constant at? Zero! This is unlikely to be the most helpful or intuitive way to understand your estimates (for example, what if you have a dichotomous predictor, what does it mean then?). Once your models get even a little bit complicated (quick, exponentiate a log-transformed value and tell me what it means!), the regression-table-alone approach becomes arguably worse than useless.
98 What is to be done? Provide predicted estimates for real, reasonable examples drawn from your dataset! For instance, if you were regressing lifetime earnings on a bunch of different predictors including years of education, gender, race, age, and height, you would, of course, start by showing your readers the table that includes all of the coefficients, standard errors, etc. Then you chould also provide some specific predicted values for "prototypical" individuals in your dataset. Regression models usually incorporate earnings as a square-root or log-transformed measure, so the table of raw model results won't be easy to interpret. It is probably far more helpful to translate the model results into estimates of how much more/less you would we estimate 30 year old woman of average height with a college degree to change if they were white vs. asian/pacific islander. These prototypical predicted values (also sometimes referred to as "marginal effects") may be presented as specific point-estimates in the text and/or using a visualization of some sort (e.g., lines plotting the predicted lifetime earnings by race over the observed range of age...). You can (and should!) even generate confidence intervals around them (But that's a whole separate rant...).
100 The point that I hope you take away is that just because you produced a regression table with some p-values and stars in it, your job is not done. You should always do the work to convey your results in a human-intelligible manner by translating the model back into some model-predicted estimates for reasonable combinations of your predictor variables. Once you've got the hang of that, you should also work on conveying the uncertainty/confidence around your predictions given the data/model.