HW 01 - Hello R!

due Tuesday, 9/20 at 11:59pm

R is the name of the programming language itself and RStudio is a convenient interface.

This homework will go through much of the same workflow we’ve demonstrated in class. The main goal is to reinforce our demo of R and RStudio, which we will be using throughout the course both to learn the statistical concepts discussed in the course and to analyze real data and come to informed conclusions.

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

An additional goal is to reinforce git and GitHub, the collaboration and version control system that we will be using 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. Before we get to that stage, however, you need to build some basic fluency in R. Today we begin with the fundamental building blocks of R and RStudio: the interface, reading in data, and basic commands.

Getting started

Clone the repo & start new RStudio project

Packages

In this lab we will work with two packages: datasauRus which contains the dataset, and tidyverse which is a collection of packages for doing data analysis in a “tidy” way. Let’s load these packages now:

library(tidyverse) 
library(datasauRus)

If you get an error, that reads \(\color{red}{\text{there is no packaged called 'datasauRus'}}\) you probably need to install the datasauRus package. Run the following in your console (watch out for capitalization). Remember that the console is the section at the bottom of RStudio:

install.packages("datasauRus")

Once you have installed the package, try running the above code again!

Data

If it’s confusing that the data frame is called datasaurus_dozen when it contains 13 datasets, you’re not alone! Have you heard of a baker’s dozen?

The data frame we will be working with today is called datasaurus_dozen and it’s in the datasauRus package. Actually, this single data frame contains 13 datasets, designed to show us why data visualization is important and how summary statistics alone can be misleading. The different datasets are marked by the dataset variable.

To find out more about the dataset, type the following in your console.

?datasaurus_dozen

A question mark before the name of an object will always bring up its help file. This command must be run in the console; alternatively, you can use

help("datasaurus_dozen")
  1. Based on the help file, how many rows and how many columns does the datasaurus_dozen file have? What are the variables included in the data frame? Add your responses to your homework assignment.

Refer to the bottom of this page for a refresher on pushing changes to GitHub!

When you’re done, commit your changes with the commit message “Added answer for Ex 1”, and push.

Let’s take a look at what these datasets are. To do so we can make a frequency table of the dataset variable:

datasaurus_dozen %>%
  count(dataset) %>%
  print(13)
## # A tibble:
## #   13 × 2
##    dataset   
##    <chr>     
##  1 away      
##  2 bullseye  
##  3 circle    
##  4 dino      
##  5 dots      
##  6 h_lines   
##  7 high_lines
##  8 slant_down
##  9 slant_up  
## 10 star      
## 11 v_lines   
## 12 wide_lines
## 13 x_shape   
## # … with 1
## #   more
## #   variable:
## #   n <int>

Matejka, Justin, and George Fitzmaurice. “Same stats, different graphs: Generating datasets with varied appearance and identical statistics through simulated annealing.” Proceedings of the 2017 CHI Conference on Human Factors in Computing Systems. ACM, 2017.

The original Datasaurus (dino) was created by Alberto Cairo in this great blog post. The other Dozen were generated using simulated annealing and the process is described in the paper Same Stats, Different Graphs: Generating Datasets with Varied Appearance and Identical Statistics through Simulated Annealing by Justin Matejka and George Fitzmaurice. In the paper, the authors simulate a variety of datasets that the same summary statistics to the Datasaurus but have very different distributions.

Data visualization and summary

  1. Plot y vs. x for the dino dataset. Then, calculate the correlation coefficient between x and y for this dataset.

Below is the code you will need to complete this exercise. Basically, the answer is already given, but you need to include relevant bits in your Rmd document and successfully knit it and view the results.

Start with the datasaurus_dozen and pipe it into the filter function to filter for observations where dataset == "dino". Store the resulting filtered data frame as a new data frame called dino_data.

dino_data <- datasaurus_dozen %>%
  filter(dataset == "dino")

There is a lot going on here, so let’s slow down and unpack it a bit.

First, the pipe operator: %>%, takes what comes before it and sends it as the first argument to what comes after it. So here, we’re saying filter the datasaurus_dozen data frame for observations where dataset == "dino".

Second, the assignment operator: <-, assigns the name dino_data to the filtered data frame.

Next, we need to visualize these data. We will use the ggplot function for this. Its first argument is the data you’re visualizing. Next we define the aesthetic mappings. In other words, the columns of the data that get mapped to certain aesthetic features of the plot, e.g. the x axis will represent the variable called x and the y axis will represent the variable called y. Then, we add another layer to this plot where we define which geometric shapes we want to use to represent each observation in the data. In this case we want these to be points, hence geom_point.

ggplot(data = dino_data, mapping = aes(x = x, y = y)) +
  geom_point()

For the second part of this exercise, we need to calculate a summary statistic: the correlation coefficient. Correlation coefficient, often referred to as \(r\) in statistics, measures the linear association between two variables. You will see that some of the pairs of variables we plot do not have a linear relationship between them. This is exactly why we want to visualize first: visualize to assess the form of the relationship, and calculate \(r\) only if relevant. In this case, calculating a correlation coefficient really doesn’t make sense since the relationship between x and y is definitely not linear (it’s dinosaurial)!

For illustrative purposes only, let’s calculate the correlation coefficient between x and y.

Start with dino_data and calculate a summary statistic that we will call r as the correlation between x and y.

dino_data %>%
  summarize(r = cor(x, y))
## # A tibble: 1 × 1
##         r
##     <dbl>
## 1 -0.0645

This is a good place to pause, knit and commit changes with the commit message “Added answer for Ex 2.” Push these changes when you’re done.

  1. Plot y vs. x for the star dataset. You can (and should) reuse code we introduced above, just replace the dataset name with the desired dataset. Then, calculate the correlation coefficient between x and y for this dataset. How does this value compare to the r of dino?

This is another good place to pause, knit, commit changes with the commit message “Added answer for Ex 3”, and push.

  1. Plot y vs. x for the circle dataset. You can (and should) reuse code we introduced above, just replace the dataset name with the desired dataset. Then, calculate the correlation coefficient between x and y for this dataset. How does this value compare to the r of dino?

You should pause again, knit, and commit changes with the commit message “Added answer for Ex 4”, and push.

Facet by the dataset variable, placing the plots in a 3 column grid, and don’t add a legend.

Finally, let’s plot all datasets at once. In order to do this we will make use of faceting, given by the code below:

ggplot(datasaurus_dozen, aes(x = x, y = y, color = dataset))+
  geom_point()+
  facet_wrap(~ dataset, ncol = 3) +
  theme(legend.position = "none")

And we can use the group_by function to generate all the summary correlation coefficients. We’ll go through these functions next week when we learn about data wrangling.

datasaurus_dozen %>%
  group_by(dataset) %>%
  summarize(r = cor(x, y)) 
  1. Include the faceted plot and the summary of the correlation coefficients in your homework write-up by including relevant code in R chunks (give them appropriate names). In the narrative below the code chunks, briefly comment on what you notice about the plots and the correlations between x and y values within each of them (one or two sentences is fine!).

You’re done with the data analysis exercises, but we’d like to do one more thing to customize the look of the report.

Resize your figures

We can customize the output from a particular R chunk by including options in the header that will override any global settings.

  1. In the R chunks you wrote for Exercises 2-5, customize the settings by modifying the options in the R chunks used to create those figures.

For Exercises 2, 3, and 4, we want square figures. We can use fig.height and fig.width in the options to adjust the height and width of figures. Modify the chunks in Exercises 2-4 to be as follows:

```{r ex2-chunk-name, fig.height=5, fig.width=5}

Your code that created the figure

```

For Exercise 5, modify your figure to have fig.height of 10 and fig.width of 6.

Now, save and knit to PDF. Once you’ve created this .pdf file, you’re done!

Commit all remaining changes, use the commit message “Done with HW 1!” and push.

Submission

In this class, we’ll be submitting .pdf documents to Canvas. Once you are fully satisfied with your homework, Knit to create a .pdf document. The pdf document you turn in should be found in the folder associated with this assignment. You may notice that the formatting/theme of the report has changed – this is expected. Refer to the file in the 9/20 HW section of the schedule on the course website for help on how to knit to PDF!

Before you wrap up the assignment, make sure all documents are updated on your GitHub repo. I will be checking these to make sure you have been practicing how to commit and push changes.

Remember – you must turn in a .pdf file to the Canvas page before the submission deadline for full credit.

Once your work is finalized in your GitHub repo, you will submit it to Canvas.

Refresher on comitting and pushing to GitHub:

Commiting changes:

Open up the GitHub Desktop application. If you have made changes to your .Rmd file or created new files, you should see it listed here.

Next, write a meaningful commit message (for instance, “Updated author name”) in the text box next to your GitHub profile image. Click the Commit to main blue button.

Of course, you don’t have to commit after every change, as 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 tell you exactly when to commit and in some cases, what commit message to use. As the semester progresses we will let you make these decisions.

Pushing changes:

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 so that others can see your changes. By others, we mean the course teaching team (your repos) in this course are private to you and us, only).

In order to push your changes to GitHub, you must have committed your changes in the previous step. At the top of the application, the third tab should have changed to say Push origin with some arrows displayed. Go ahead and push!