From: aaronshaw Date: Thu, 30 May 2019 02:20:05 +0000 (-0500) Subject: w09 r lecture materials X-Git-Url: https://code.communitydata.science/stats_class_2019.git/commitdiff_plain/f2036e416b850a6c3cd936db4574de3dd466ee27?hp=fb2e2b741c48f616bb32e074de43048e315875a7 w09 r lecture materials --- diff --git a/r_lectures/w09-R_lecture.Rmd b/r_lectures/w09-R_lecture.Rmd new file mode 100644 index 0000000..bf750d7 --- /dev/null +++ b/r_lectures/w09-R_lecture.Rmd @@ -0,0 +1,81 @@ +--- +title: "Week 9 R Lecture" +author: "Aaron Shaw" +date: "May 30, 2019" +output: html_document +--- + +```{r setup, include=FALSE} +knitr::opts_chunk$set(echo = TRUE) +``` + +For all of the examples this week, I'll work with the `population.tsv` dataset from back in [Week 5](https://communitydata.science/~ads/teaching/2019/stats/data/week_05/). The following lines of code load it and clean it a bit. Since we've worked with this dataset before I will not revisit the process of "getting to know" it. + +```{r} +d <- read.delim(url("https://communitydata.science/~ads/teaching/2019/stats/data/week_05/population.tsv")) + +d$j <- as.logical(d$j) +d$l <- as.logical(d$l) +d$k <- factor(d$k, + levels=c(1,2,3), + labels=c("some", "lots", "all")) + +d <- d[complete.cases(d),] +``` + +## Transformations + +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). + +### Interaction terms + +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. + +```{r} +m.base <- formula(y ~ x + j) +summary(lm(m.base, data=d)) + + +m.i <- update.formula(m.base, . ~ . + I(x*j)) +summary(lm(m.i, data=d)) +``` + +### Polynomial (square, cube, etc.) terms + +Polynomial terms can easily be created using `I()` as well: + +```{r} +m.poly <- update.formula(m.base, . ~ . + I(x^2)) +summary(lm(m.poly, data=d)) +``` +Need higher order polynomials? Try including `I(x^3)` and so on... + +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: + +```{r} +m.poly2 <- formula(y ~ j + poly(x,2)) +summary(lm(m.poly2, data=d)) +``` +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)`). + +### Log-transformations + +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: + +```{r} +m.log <- update.formula(m.base, . ~ log1p(x) + j) +summary(lm(m.log, data=d)) +``` +Keep in mind that you can use other bases for your logarithmic transformations. Check out the documentation for `log()` for more information. + +## Interpreting regression results wiht model-predicted values + +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. + +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. + +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. + +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...). + +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. \ No newline at end of file diff --git a/r_lectures/w09-R_lecture.html b/r_lectures/w09-R_lecture.html new file mode 100644 index 0000000..b5f76f4 --- /dev/null +++ b/r_lectures/w09-R_lecture.html @@ -0,0 +1,376 @@ + + + + + + + + + + + + + + + +Week 9 R Lecture + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + +

For all of the examples this week, I’ll work with the population.tsv dataset from back in Week 5. The following lines of code load it and clean it a bit. Since we’ve worked with this dataset before I will not revisit the process of “getting to know” it.

+
d <- read.delim(url("https://communitydata.science/~ads/teaching/2019/stats/data/week_05/population.tsv"))
+
+d$j <- as.logical(d$j)
+d$l <- as.logical(d$l)
+d$k <- factor(d$k,
+               levels=c(1,2,3),
+               labels=c("some", "lots", "all"))
+
+d <- d[complete.cases(d),]
+
+

Transformations

+

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).

+
+

Interaction terms

+

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.

+
m.base <- formula(y ~ x + j)
+summary(lm(m.base, data=d))
+
## 
+## Call:
+## lm(formula = m.base, data = d)
+## 
+## Residuals:
+##     Min      1Q  Median      3Q     Max 
+## -4.9986 -2.4964  0.0199  2.5803  5.1769 
+## 
+## Coefficients:
+##             Estimate Std. Error t value Pr(>|t|)    
+## (Intercept) -0.07040    0.12358  -0.570    0.569    
+## x            2.98853    0.03016  99.103   <2e-16 ***
+## jTRUE        0.06583    0.13818   0.476    0.634    
+## ---
+## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
+## 
+## Residual standard error: 3.01 on 1897 degrees of freedom
+## Multiple R-squared:  0.8383, Adjusted R-squared:  0.8381 
+## F-statistic:  4917 on 2 and 1897 DF,  p-value: < 2.2e-16
+
m.i <- update.formula(m.base, . ~ . + I(x*j))
+summary(lm(m.i, data=d))
+
## 
+## Call:
+## lm(formula = m.i, data = d)
+## 
+## Residuals:
+##     Min      1Q  Median      3Q     Max 
+## -5.0670 -2.5254 -0.0188  2.5669  5.4437 
+## 
+## Coefficients:
+##             Estimate Std. Error t value Pr(>|t|)    
+## (Intercept)  0.02816    0.14742   0.191    0.849    
+## x            2.94958    0.04380  67.340   <2e-16 ***
+## jTRUE       -0.12630    0.20894  -0.604    0.546    
+## I(x * j)     0.07402    0.06039   1.226    0.220    
+## ---
+## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
+## 
+## Residual standard error: 3.01 on 1896 degrees of freedom
+## Multiple R-squared:  0.8384, Adjusted R-squared:  0.8382 
+## F-statistic:  3279 on 3 and 1896 DF,  p-value: < 2.2e-16
+
+
+

Polynomial (square, cube, etc.) terms

+

Polynomial terms can easily be created using I() as well:

+
m.poly <- update.formula(m.base, . ~  . + I(x^2))
+summary(lm(m.poly, data=d))
+
## 
+## Call:
+## lm(formula = m.poly, data = d)
+## 
+## Residuals:
+##     Min      1Q  Median      3Q     Max 
+## -5.1627 -2.5549  0.0013  2.5957  5.1762 
+## 
+## Coefficients:
+##              Estimate Std. Error t value Pr(>|t|)    
+## (Intercept) -0.004589   0.147378  -0.031    0.975    
+## x            2.922286   0.086249  33.882   <2e-16 ***
+## jTRUE        0.062671   0.138247   0.453    0.650    
+## I(x^2)       0.008989   0.010965   0.820    0.412    
+## ---
+## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
+## 
+## Residual standard error: 3.01 on 1896 degrees of freedom
+## Multiple R-squared:  0.8383, Adjusted R-squared:  0.8381 
+## F-statistic:  3277 on 3 and 1896 DF,  p-value: < 2.2e-16
+

Need higher order polynomials? Try including I(x^3) and so on…

+

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:

+
m.poly2 <- formula(y ~ j + poly(x,2))
+summary(lm(m.poly2, data=d))
+
## 
+## Call:
+## lm(formula = m.poly2, data = d)
+## 
+## Residuals:
+##     Min      1Q  Median      3Q     Max 
+## -5.1627 -2.5549  0.0013  2.5957  5.1762 
+## 
+## Coefficients:
+##              Estimate Std. Error t value Pr(>|t|)    
+## (Intercept)   7.69671    0.09725  79.143   <2e-16 ***
+## jTRUE         0.06267    0.13825   0.453    0.650    
+## poly(x, 2)1 298.44632    3.01172  99.095   <2e-16 ***
+## poly(x, 2)2   2.46880    3.01155   0.820    0.412    
+## ---
+## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
+## 
+## Residual standard error: 3.01 on 1896 degrees of freedom
+## Multiple R-squared:  0.8383, Adjusted R-squared:  0.8381 
+## F-statistic:  3277 on 3 and 1896 DF,  p-value: < 2.2e-16
+

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)).

+
+
+

Log-transformations

+

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:

+
m.log <- update.formula(m.base, . ~ log1p(x) + j)
+summary(lm(m.log, data=d))
+
## 
+## Call:
+## lm(formula = m.log, data = d)
+## 
+## Residuals:
+##     Min      1Q  Median      3Q     Max 
+## -7.1239 -2.8823 -0.1261  2.5982 13.4045 
+## 
+## Coefficients:
+##             Estimate Std. Error t value Pr(>|t|)    
+## (Intercept)  -2.9937     0.1813  -16.52   <2e-16 ***
+## log1p(x)      9.8895     0.1288   76.79   <2e-16 ***
+## jTRUE         0.2134     0.1694    1.26    0.208    
+## ---
+## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
+## 
+## Residual standard error: 3.691 on 1897 degrees of freedom
+## Multiple R-squared:  0.7569, Adjusted R-squared:  0.7566 
+## F-statistic:  2953 on 2 and 1897 DF,  p-value: < 2.2e-16
+

Keep in mind that you can use other bases for your logarithmic transformations. Check out the documentation for log() for more information.

+
+
+
+

Interpreting regression results wiht model-predicted values

+

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.

+

This was covered in one of the resources 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.

+

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.

+

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…).

+

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.

+
+ + + + +
+ + + + + + + +