R is the name of the programming language itself and RStudio is a convenient user interface.
The main goal of this lab is to review the basics of R and RStudio. We will use these tools throughout this course to analyze and make conclusions from real-world data.
git is a version control system (like “Track Changes” features from Microsoft Word but more powerful) and GitHub is the home for your Git-based projects on the internet (like DropBox but better).
An additional goal is to introduce you to git and GitHub, which is the version control and collaboration system we will use throughout the course.
As the labs progress, you are encouraged to explore beyond what the labs dictate; a willingness to experiment will make you a much better programmer and statistician. This lab is a brief review of the fundamental building blocks of R and RStudio: the interface, reading in data, and basic data wrangling and graphing functions. If you’re new to R or would like additional practice, there are resources listed at the end of the lab instructions.
Today’s lab will focus on fundamental building blocks of R and RStudio: the interface, reading in data, and basic commands. Starting next week, the labs will focus on concepts more specific to regression analysis. Today’s lab will be individual, to give you a chance to become more familiar with the workflow. In future labs you will work in teams, and learn how to collaborate using GitHub to produce a single lab report as a team.
Each of your assignments will begin with steps in this section. You saw your TA demonstrate these steps, and they’re outlined in detail below. Going forward, each lab will begin with a “Getting started” section but the details will become more sparse as the semester progresses. You can always refer back to this lab for a detailed list of the steps involved for getting started with an assignment.
Click on the green Clone or download button, select Use HTTPS (this might already be selected by default, and if it is, you’ll see the text Clone with HTTPS as in the image below). Click on the clipboard icon to copy the repo URL.
Go to https://vm-manage.oit.duke.edu/containers and login with your Duke NetId and Password.
Click to log into the Docker container STA 210 - Regression Analysis. You should now see the RStudio environment.
Go to File ➡️ New Project ➡️ Version Control ➡️ Git.
Copy and paste the URL of your assignment repo into the dialog box Repository URL. You can leave Project Directory Name empty. It will default to the name of the GitHub repo.
Click Create Project, and the files from your GitHub repo will be displayed the Files pane in RStudio.
There is one more piece of housekeeping we need to take care of before we get started. Specifically, we need to configure your git so that RStudio can communicate with GitHub. This requires two pieces of information: your name and email address.
To do so, you will use the use_git_config()
function from the usethis
package.
Type the following lines of code in the console in RStudio filling in your name and email address.
The email address is the one tied to your GitHub account.
For example, mine would be
If you get the error message
then you need to install the usethis
package. Run the following code in the console to install the package. Then, rerun the use_git_config
function with your GitHub username and email address associated with your GitHub account.
Once you run the configuration code, your values for user.name
and user.email
will display in the console. If your user.name
and user.email
are correct, you’re good to go! Otherwise, run the code again with the necessary changes.
Below are the general components of an RStudio project.
Below are the general components of an RMarkdown file.
To get more details about the RStudio project, RMarkdown file, and just R in general, read Getting Started in Data Visualization by Kieran Healy.
We will use the following package in today’s lab.
If you need to install the package, run the code below in the console.
The top portion of your R Markdown file (between the three dashed lines) is called YAML. It stands for “YAML Ain’t Markup Language”. It is a human friendly data serialization standard for all programming languages. All you need to know is that this area is called the YAML (we will refer to it as such) and that it contains meta information about your document.
Before we introduce the data, let’s update the name and date in the YAML.
Open the R Markdown (Rmd) file in your project, input your name for the author name and today’s date for the date, and knit the document.
Next, go to the Git pane in RStudio.
If you have made changes to your Rmd file, you should see it listed here. Click on it to select it in this list and then click on Diff. This shows you the difference between the last committed state of the document and its current state with your changes. If you’re happy with these changes, write “Update author name” in the Commit message box and click Commit.
You don’t have to commit after every change, this would get quite cumbersome. You should consider committing states that are meaningful to you for inspection, comparison, or restoration. In the first few assignments, we will provide some guidance on when to commit and an example commit message.
Now that you have made an update and committed this change, it’s time to push these changes to the web! Or more specifically, to your repo on GitHub. Why? So that others can see your changes. And by others, we mean the course teaching team. (Your repos in this course are private and can only be seen by you and the teaching team.)
In order to push your changes to GitHub, click Push. This will prompt a dialogue box where you first need to enter your user name, and then your password. This might feel cumbersome. Bear with me… We will teach you how to save your password so you don’t have to enter it every time. But for this one assignment you’ll have to manually enter each time you push in order to gain some experience with it.
Make sure you push all the files from the Git pane to your assignment repo on GitHub. The Git pane should be empty after you push. If it’s not, click the box next to the remaining files, write an informative commit message, and push.
Today’s data comes from the Durham Open Data a program managed by the City of Durham’s Technology Solutions Department and the County of Durham’s Information Services & Technology Department to provide open data about our community. You can read more about their mission here.
In this lab, we will focus on data about the proposed and existing outdoor trails in Durham, NC. The data is located in the durham_trails.csv file located in the data folder. Use the code below to read in the .csv file and save it in the RStudio environment as a data frame called trails
.
A full list of the variables in the dataset is available here. For today’s analysis, we will primarily focus on the following variables:
status |
Whether the trail is proposed or existing |
dogwalking |
Whether dogs are allowed on the trail |
length |
Length of the trail in miles |
Write your answers in complete sentences and show all code and output.
Before doing any analysis, we may want to get quick view of the data. This is a useful thing to do after importing data to see if the data imported correctly. One way to do this, is to look at the actual dataset. Type the code below in the console to view the entire dataset.
Notice that the View(trails)
command was run in the console and not in a code chunk in the RMarkdown file. By running the View(trails)
in the console, the dataset displays in your RStudio environment but not in the output from your RMarkdown file.
Now that we’ve had a quick view of the dataset, let’s get more details about its structure. Sometimes viewing a summary of the data structure is more useful than viewing the raw data, especially if the dataset has a large number of observations and/or rows. Run the code below to use the glimpse
function to see a summary of the trails
dataset.
How many observations are in the trails
dataset? How many variables?
Before conducting statistical inference (or eventually fitting regression models), we need do some exploratory data analysis (EDA). Much of EDA consists of visualizing the data but it also includes calculating summary statistics for the variables in our dataset. Let’s begin by examining the distribution of status
with a data visualization and summary statistics.
What is a type of graph that’s appropriate to visualize the distribution of status
? Fill in the ggplot
code below to plot the distribution of status
. Include informative axis labels and title on the graph.
Then, calculate the proportion of observations in each category of status
by completing the code below.
ggplot(data = trails, aes(x = status)) +
__________ +
labs(x = "_________",
y = "_________",
title = "__________")
filter
function to create a subset consisting only of trails that currently exist and have a value reported for length
. Assign the subset the name current_trails
. (Hint: There should be 1054 observations in current_trails.)Check your lab-01 repo on the GitHub website (you may need to refresh the page in your browser) to ensure that all of the files are up-to-date.
This is a good place to knit, commit, and push changes to your remote lab-01 repo on GitHub. Be sure to write an informative commit message (e.g. “Completed exercises 1 - 3”), and push every file to GitHub by clicking the checkbox next to each file in the Git pane. After you push the changes, the Git pane in RStudio should be empty."
Use current_trails
for Exercises 4 - 7.
Let’s examine the distribution of length
. One important part of EDA is creating data visualizations to see the shape, center, spread, and outliers in a distribution. Data visualizations are also useful for examining the relationship between multiple variables. There are a lot of ways to make data visualizations in R; we will use the functions available in the ggplot2
package.
Make a graph to visualize the distribution of length
. Include an informative title and axis labels.
See Section 7.3.1 “Visualizing Distributions” or the ggplot2 reference page for details and example code.
summarise
function to calculate various summary statistics for the variable length
. You can use the summarise reference page for more information about the function and example code.current_trails %>%
summarise(min = __________,
q1 = __________,
median = __________,
q3 = __________,
max = __________,
iqr = __________,
mean = __________,
std_dev = __________
)
Describe the distribution of length
. Your description should include comments about the shape, center, spread, and any potential outliers. Use the graph from Exercise 4 and relevant summary statistics from Exercise 5 in your description.
We want to limit the analysis to trails that are more likely intended for day hikes, rather than multi-day hikes and camping. Therefore, let’s remove the extreme outliers from the data for this analysis and only consider those trails that are 15 miles or shorter.
Filter the dataset to remove the extreme outliers. Be sure to save the updated dataset, so you can use it for the remainder of the lab.
This is a good place to knit, commit, and push changes to your remote lab-01 repo on GitHub. Be sure to write informative commit message (e.g. “Completed exercises 4 - 7”), and push every file to GitHub by clicking the checkbox next to each file in the Git pane. After you push the changes, the Git pane in RStudio should be empty."
dogwalking
.
dogwalking
in the dataset? Show the code and output to support your answer.dogwalking
? In other words, what does a missing value of dogwalking
indicate?dogwalking
with the appropriate value. Then, display the distribution of dogwalking
to check that the missing values were correctly imputed.Now that we’ve completed the univariate EDA (i.e. examining one variable at a time), let’s examine the relationship between the length of the trail and whether dog walking is allowed. Make a graph to visualize the relationship between length
and dogwalking
and calculate the appropriate summary statistics. Include informative axis labels and title on your graph.
Describe the relationship between length
and dogwalking
. In other words, describe how the distribution of length
compares between trails that allow dog walking versus those that don’t. Include information from the graph and summary statistics from the previous exercise in your response.
This is a good place to knit, commit, and push changes to your remote lab-01 repo on GitHub. Be sure to write informative commit message (e.g. “Completed exercises 8 - 11”), and push every file to GitHub by clicking the checkbox next to each file in the Git pane. After you push the changes, the Git pane in RStudio should be empty."
We’d like to use the data from the trails in Durham to make more general conclusions about trails in urban areas in the southeastern United States. We will reasonably consider the trails in Durham representative of the trails in other urban areas in the southeastern United States.
Over the next few questions, will use statistical inference to assess whether there is a difference in the mean length of trails that allow dog walking versus those that don’t.
The following conditions must be met when we conduct statistical inference on the difference in means between two groups. For each condition, specify whether it is met and a brief explanation of your reasoning.
While we have observed a difference in the mean length in trails for those that allow dog-walking versus those that don’t, let’s assess if there is enough evidence to consider the difference “statistically significant” or if it appears to be due to random chance.
The null and alternative hypotheses are written in statistical notation below. State the hypotheses in words in the context of this analysis.
\[H_0: \mu_1 - \mu_2 = 0 \\ H_a: \mu_1 - \mu_2 \neq 0\]
Type ?t.test
in the console to learn more about the function and its options.
t.test
function to calculate the test statistic and p-value. Replace response
with the variable we’re interested in drawing conclusions about and group_var
with the variable used to define the two groups.t.test(response ~ group_var, data = ________,
alternative = "___________",
conf.level = 0.99) #less, greater, or two.sided
You’re done and ready to submit your work! Knit, commit, and push all remaining changes. You can use the commit message “Done with Lab 1!”, and make sure you have pushed all the files to GitHub (your Git pane in RStudio should be empty) and thatall documents are updated in your repo on GitHub. Then submit the assignment on Gradescope following the instructions below.
Once your work is finalized in your GitHub repo, you will submit it to Gradescope. Your assignment must be submitted on Gradescope by the deadline to be considered “on time”.
To submit your assignment:
Go to http://www.gradescope.com and click Log in in the top right corner.
Click School Credentials ➡️ Duke NetID and log in using your NetID credentials.
Click on the STA 210 Regression Analysis course.
Click on the assignment, and you’ll be prompted to submit it.
Select your lab-01-review-r-
repo and choose “master” for the branch.
Click Upload. You should receive an email to confirm that the assignment has been submitted.
Notes: - You can see what has been submitted by click “Code” at the top of the page. We will be grading the PDF file, so please make sure that has all of your final code, output, and narrative.
Exploratory Data Analysis (Ex. 1 - 11) | 28 |
Statistical Inference (Ex. 12 - 16) | 15 |
Lab attendance & participation | 3 |
Narrative in full sentences | 2 |
At least 3 informative commit messages | 2 |
Total | 50 |
Chapter 2: Get Started Data Visualization by Kieran Healy
Chapter 3: Data visualization in R for Data Science by Hadley Wickham
RStudio Cloud Primers
Visualization in R using ggplot2 workshop by the Center for Data and Visualization Sciences