Getting started

  1. Clone your repo appex05-[github_name] to create a new project in RStudio Cloud under the STA 199 class space.

  2. Configure git

    library(usethis)
    use_git_config(user.name="your name", user.email="your email")

Packages and Data

We’ll make use of the following packages.

library(tidyverse)
library(ggpol)

Tasks

Task 1

Write a function called center_measures that has one argument - x a numeric vector. The function should return the mean and median of x. Below is some sample code.

nums <- c(10, 5, -1, 0, 4)
c(mean(nums), median(nums))
#> [1] 3.6 4.0
center_measures <- function() {
  
  
  
}

Task 2

Turn the following code into a function. How many arguments does it need? What is a good name for this function? Assume x will be a nonnegative numeric vector.

x / sum(x)

Task 3

congress <- read_csv("http://www2.stat.duke.edu/~sms185/data/politics/congress_long.csv")
congress

Write a for loop to compute the number of unique values in each column of tibble congress. Try to stay within the tidyverse syntax as much as possible.

You may find function length() useful. Below are some examples of it in action.

length(1:10)
#> [1] 10
length(c("a", "ab", "abc", "abcd"))
#> [1] 4
length(seq(from = 2, to = 10, by = 2))
#> [1] 5

Task 4

Function plot_congress() is similar to the function in the slides. I added some annotation so we know the year and legislative branch.

Run the example below to see the change that was made with annotate().

plot_congress(year = 2019, leg_branch = "house")

Use function plot_congress() to create a GIF by creating plots for each year in object congress from 1993 to 2019. You’ll need to put your function call inside print and figure out the loop sequence. Once you are done, remove chunk option eval=FALSE.

for () {
  print({
    
  })
}

Slide notes

References

  1. Grolemund, G., & Wickham, H. (2020). R for Data Science. R4ds.had.co.nz. Retrieved 9 February 2020, from https://r4ds.had.co.nz/

  2. erocoar/ggpol. (2020). GitHub. Retrieved 9 February 2020, from https://github.com/erocoar/ggpol