Complete all Questions and submit your final PDF or HTML (either works!) under Assignments in Canvas.
The Goal
Last lab, we focused on learning to fit a least-squares linear regression (LSLR) line—that is, finding the values of \(\hat{\beta}_0\) and \(\hat{\beta}_1\)—using R. We looked specifically at coffee data and worked through the steps of building and interpreting the LSLR line.
The choice to use an LSLR model involves assumptions. We already know that we should not use a linear model if the relationship between \(X\) and \(Y\) is not linear. In a graph, the relationship between \(X\) and \(Y\) should look approximately like a line. This is called the form (shape) condition, and it is one of the first things we check when considering LSLR.
Today, we will explore alternative modeling choices when the shape of the relationship is not a line.
Remember that now is a good time to clear your Environment if you have not already. We created many objects in the last lab, and today’s work will be easier if your Environment is clean.
The Data
The data for today’s lab concern bluegills, a type of freshwater fish found throughout North America. A client has provided data on \(n=170\) bluegill fish and wants to understand how fish length changes with age. This information is important because bluegills are popular sport fish.
The client is responsible for determining the minimum length a caught bluegill must reach before it may be kept. A fish longer than this length minimum may be kept, whereas a fish below the minimum must be returned to the water.
The client knows that bluegills reproduce most during their first four years of life. Therefore, it is important that fish aged four years or younger are not removed from the water, helping the species continue to thrive.
The client has asked you (1) to determine an appropriate length minimum and (2) to describe the relationship between \(X=\) fish age and \(Y=\) fish length.
Download the data
Download bluegills.csv from Canvas, or using this link
and import it into R. You can use the same procedure as in Lab 2:
- Step 1: Look at the upper-right panel of RStudio (the Environment tab).
- Step 2: Click Import Dataset or Import.
- Step 3: Choose Text (base) or From CSV, depending on your computer.
- Step 4: Find and select
bluegills.csv. - Step 5: In the lower-right panel, locate the
generated code, which should resemble
bluegills <- read.csv("SOME STUFF HERE"). - Step 6: Copy that entire line of code.
- Step 7: Insert an R code chunk in this R Markdown file.
- Step 8: Paste the line into the code chunk and run it using the green arrow.
You are now ready to work with the data.
To make the knitted document look professional, the setup chunk at the top uses
knitr::opts_chunk$set(echo = FALSE, message = FALSE, warning = FALSE)
Your code will still run and its results will appear, but the code itself, package messages, and warnings will be hidden in the final document.
EDA
The first step in an analysis is exploratory data analysis (EDA), which usually includes making plots to understand the data. This data set has only two variables, so we will focus on their relationship. Fish length, measured in millimeters, is the response variable (\(Y\)).
Question 1
Create an appropriate visualization to explore the relationship between \(X=\) fish age (in years) and \(Y=\) fish length (in millimeters). Label the axes Fish Age in years and Fish Length in mm, and title the graph Figure 1.
Question 2
Describe the relationship between the two variables.
Our specific goal is to determine how long we expect fish to be once they are more than four years old. In other words, given a fish’s age (\(X\)), can we predict its length (\(Y\))? We hope to use this information to determine the length minimum.
Because we are particularly interested in Age = 4, add a vertical
line to the scatterplot using
+ geom_vline(xintercept = 4).
Question 3
Create the same graph as you did in Question 1, but now add a
vertical line to your graph at Age = 4. Make sure you have labeled your
axes “Fish Age” and “Fish Length”, and title your graph Figure 2. Choose
to either (1) change the color(col) of the line or (2) make
the line dashed by adding lty = 2. For option 2, your code
will look like geom_vline(xintercept = , lty = 2)
Note: You can use numbers other than 2 to choose a different line
type. You can also change the thickness of the line by adding
size = 1.5 or some other value greater than 1.
Question 4
Based strictly on the graph, what value might you choose for the length minimum? Explain your choice. There are many reasonable answers; the goal is to explain your thinking.
Question 5
Re-create your graph from Question 3 and add a horizontal line at the length minimum you proposed. Label the axes Fish Age in years and Fish Length in mm, and title the graph Figure 3.
Hint: A vertical line is added with
geom_vline() and positioned using
xintercept =. For a horizontal line, use
geom_hline() and specify its position on the \(y\)-axis.
A graph can give us an initial estimate of the length minimum. To obtain a more precise answer, we want to build a statistical model for the relationship between fish age (\(X\)) and fish length (\(Y\)).
Question 6
Based on what you have observed, does the shape of the relationship suggest that LSLR is appropriate? Explain briefly.
Considering Other Options
LSLR is not the only regression model available. We can fit many shapes other than a straight line.
Question 7
What regression model might be more appropriate than LSLR for these data?
Your proposed model has a nonlinear shape. When considering a particular model shape, it is helpful to draw the fitted curve and visually assess whether the choice is reasonable.
To add an LSLR line to a scatterplot, use
+ stat_smooth(formula = y ~ x, method = "lm", se = FALSE)
To add a polynomial regression curve, use
+ stat_smooth(formula = y ~ poly(x, NUMBER), method = "lm", se = FALSE)
where NUMBER is replaced by the degree of the
polynomial.
Question 8
Re-create your graph from Question 1 and add the fitted model you proposed in Question 7. Label the axes and title the graph Figure 4. Visually, does this shape appear to be a reasonable choice? If you are stuck, refer to the slides from the previous class.
Now that we have chosen a type of regression model, the next step is to build it. This will allow us to predict the length of a four-year-old fish and address the client’s question.
Storing in R
Previously, we fitted a regression model using code such as
lm(y ~ x, data = dataset)
Running this code displays estimates of \(\hat{\beta}_0\) and \(\hat{\beta}_1\). However, R calculates and retains much more information, including fitted values, residuals, and \(R^2\). To access this information conveniently, we store the fitted model as an object.
For example, the following code assigns the value 4 to an object
named z:
## [1] 4
Question 9
Before running the code, what output do you expect from
4*z + 2?
Question 10
Assign the number 6 to an object named m. Show the
output obtained when you run 5*m + 4 in a code chunk.
We can also store more complicated objects. For practice, fit an LSLR model relating fish length to age—even though we already suspect that the relationship is not linear.
lm(length ~ age, data = bluegills)
Store the result under the name LSLRmodel:
LSLRmodel <- lm(length ~ age, data = bluegills)
Typing LSLRmodel displays the coefficient estimates.
Storing the model also lets us retrieve other components. For example,
use
LSLRmodel$residuals
to access the residuals.
Question 11
What is the residual for the first row in the data set?
Use
LSLRmodel$fitted.values
to access the fitted value \(\hat{y}_i\) for every row.
Question 12
What is the value of \(\hat{y}_1\) for the first row in the data set?
Printing all residuals and fitted values would add hundreds of
numbers to the final document. After using these commands, prevent them
from printing by placing # at the beginning of each
line:
Creating the Actual Regression Model
In the previous section, we fitted an LSLR model only to practice creating and storing model objects. Now build the model you believe is appropriate.
Question 13
Look back at Question 8, when you choose a shape that you think is appropriate to represent the relationship between X and Y. This shape should correspond to one of the types of regression models we have learned in class.
Fit this model in R and store it under the name
fishmodel. Then write the fitted model, including the
numerical estimates of all \(\hat{\beta}\) coefficients.
Hint: fishmodel$coefficients is one way to
obtain the coefficient estimates.
Question 14
Using your model from Question 13, what is the residual for the third row in the data set? You may use R rather than computing it by hand.
Assessing Model Fit
Before using the model for prediction, we need to describe how well it fits the data. If the model fits poorly, conclusions and predictions based on it may be unreliable.
One measure of model fit is
\[ R^2 = 1-\frac{RSS}{TSS}. \]
Question 15
Why is RSS needed to compute \(R^2\)? In other words, what does RSS measure, and why is that information relevant to \(R^2\)?
Run summary(fishmodel) to find the \(R^2\), reported in the output as
Multiple R-squared.
Question 16
Your client asks what the value of \(R^2\) means and why it is helpful. Provide a short reply.
Writing Check, Part 1: There is no single required wording; this response will be graded for any reasonable answer.
Statistical concepts can be explained formally using notation and technical terminology. That style is important when communicating with statisticians and data scientists. When communicating with a client, however, we should avoid terms that may be confusing or misleading to someone without a statistics background.
Review your answer to Question 16. Did you use terms such as variance, variability, \(X\), or \(Y\)? A client-centered explanation should instead connect the idea directly to the client’s data and goals. Effective statistical communication requires adapting an explanation to the audience rather than simply repeating a memorized definition.
Question 17
Rewrite your answer to Question 16 without technical terms such as variance or variability. Connect your explanation specifically to the client’s goals and the bluegill data.
Writing Check, Part 2: This response will be graded based on whether you improved Question 16 by focusing on the client.
Making Recommendations
With the model fitted and assessed, we are ready to recommend a length minimum.
Question 18
Using your fitted model, what is the predicted fish length for a four-year-old bluegill? Show your work using appropriate notation.
Question 19
What minimum length do you recommend before a caught bluegill may be kept? Explain why you chose this value.
Adapted by Tuhin Majumder from STA 112 Lab 3 by Nicole Dalzell, licensed under the Creative Commons Attribution–NonCommercial 4.0 International License. Original: https://rpubs.com/MST256/STA112_Lab3.