Lab Quiz 03 Info

Author

Stat220 – W25

Our third lab quiz is scheduled for Friday of Week 7. The first half of class will cover new content, and the second half of class you will complete the in-person portion of the lab quiz. The format of this lab quiz will remain the same as Lab Quiz 2.

Guidelines

This is a closed note, closed internet resources, closed other people lab quiz. I want to see what’s in your brain! You may use the cheat sheets provided by me, but otherwise you may not use any resources.

The lab quizzes are not written to be tricky or very difficult. If you’ve been completing the in-class activities and the homework, and putting the time and effort in to understand them, you should do well on the lab quizzes.

Format

The reason I give lab quizzes is because your life will be easier if you know how to do basic tasks in R “on the fly”. I also want to see what you know and not just what you can do with access to your resources. However, I also know this is not how data science works in the real world, and so there are two portions to the lab quiz.

  1. The required in-class portion (“first pass”)
  • Pencil-and-paper questions
  • Cheat sheets provided by me but no other resources
  • Designed to assess what you know “on the fly” without access to resources
  1. An optional R-based “second pass” at the questions
  • .qmd format similar to homework
  • Allowed to use materials from class (slides, activities, notes, homework, etc.) but no out-of-class resources (google, textbooks, ChatGPT or other LLMs, StackOverflow, etc.)
  • Designed to assess your coding skills and whether you can figure things out with access to class resources and R help pages

Your score on the quiz will be the average of the two scores, unless you do not submit the revision, in which case your score will only be in your in-class score. If you earn 100% on the in-class portion, your overall score will be 100% and I will not grade your revision.

Skills

The third quiz will assess your proficiency working with strings and with basic programming concepts in R (functions, if statements, for loops, across(), and map).

Strings

  • Given a string, subset or detect some portion of it
    • str_sub, str_subset, str_extract, str_detect, etc.
  • Given two strings, use str_c to concatenate them
  • Given a simple regular expression, state what will be matched
    • Literal characters, special characters (\\d, \\w, [:alpha:], \\n, \\), anchors for start/end characters (^ and $), quantifiers (+, *, {n}, {n,}, {n,m})

Functions

  • (In-class) Read and explain what a function is doing / (Take-home) Use function() to build an R function
  • Specify required arguments and default values
  • Understand how to return a value or object
  • Use a logical statement to control the flow of the function

Iteration

  • Be able to write a for loop to accomplish an iterative task
    • Preallocate storage
    • Define an index to iterate through
  • Be able to read a for loop and determine what it’s doing
  • Use across() and where() to apply {dplyr} functions to columns in a dataset
  • Explain what a map command is doing
  • Write a basic map command for group-wise data operations

Grading

For the in-class portion, each question is worth 1 point, graded as “successful” (almost entirely correct), “not successful” (missing a key component), or “half credit” (mostly correct).

For the out-of-class revision, each question is worth 1 point, graded as “successful” (correct), “not successful” (missing a key component), or “half credit” (mostly correct). Since you will be able to run the code, you will only receive full credit for fully correct solutions.

Revision

The in-class portion will be a pencil-and-paper quiz. After class, I will make everyone a repository on github with a .qmd version of the quiz. (The questions will remain essentially the same). The revision is totally optional. You will work on the repository just like homework and submit via gradescope if you wish to turn it in.

  • The in-class portion is worth 10 points
  • The out-of-class “second pass” is worth 10 points
  • If you don’t submit the revision on gradescope, your quiz will be out of 10 points and if you do submit the revision your quiz will be out of 20 points.

The revision is due before class starts on Monday. You may use the cheat sheets, materials from our class (slides, activities, notes, your homework, etc.), and the built-in help pages within RStudio. You may not use textbooks, LLMs, search engines, stack overflow, etc. to complete the revision. If your submission contains code that did not appear in our course materials, you must include an explanation for where it came from (e.g. in what context you learned that code). Otherwise, you will not receive credit for that problem and may be reported to the Academic Standing Committee.

Practice Questions

Data

The nycflights23 package contains information about all flights that departed from NYC (e.g. EWR, JFK and LGA) in 2023. The main data is in the flights data frame, but there are additional data sets which may help understand what causes delays, specifically:

  • weather: hourly meteorological data for each airport
  • planes: construction information about each plane
  • airports: airport names and locations
  • airlines: translation between two letter carrier codes and names

Questions

Given a string, subset some portion of it

One of the columns in the airports dataset is the name of the airport. Most airports with international flights have the word “International” in them.

airports 
# A tibble: 1,251 × 8
   faa   name                                 lat    lon   alt    tz dst   tzone
   <chr> <chr>                              <dbl>  <dbl> <dbl> <dbl> <chr> <chr>
 1 AAF   Apalachicola Regional Airport       29.7  -85.0    20    -5 A     Amer…
 2 AAP   Andrau Airpark                      29.7  -95.6    79    -6 A     Amer…
 3 ABE   Lehigh Valley International Airpo…  40.7  -75.4   393    -5 A     Amer…
 4 ABI   Abilene Regional Airport            32.4  -99.7  1791    -6 A     Amer…
 5 ABL   Ambler Airport                      67.1 -158.    334    -9 A     Amer…
 6 ABQ   Albuquerque International Sunport   35.0 -107.   5355    -7 A     Amer…
 7 ABR   Aberdeen Regional Airport           45.4  -98.4  1302    -6 A     Amer…
 8 ABY   Southwest Georgia Regional Airport  31.5  -84.2   197    -5 A     Amer…
 9 ACK   Nantucket Memorial Airport          41.3  -70.1    47    -5 A     Amer…
10 ACT   Waco Regional Airport               31.6  -97.2   516    -6 A     Amer…
# ℹ 1,241 more rows

Fill in the code to create a new logical column called international based on whether the name of the airport contains the word “international”.

airports |>
  mutate(
    international = _______________________________________
  )

Given two strings, use str_c to concatenate them

The flights dataset contains a carrier column (e.g. “UA”) and a flight number column (e.g. 1480). Fill in the code below to create a new column called flight_code that combines these two columns separated by a hyphen (e.g. “UA-1480”).

flights |> 
  select(carrier, flight) |> 
  mutate(
    flight_code = ______(___________, ___________, sep = ____)
  )

Given a simple regular expression, state what will be matched

The following code creates a vector of all of the airport names. Explain what each of the following str_subset commands will return.

airport_names <- airports$name
  1. str_subset(airport_names, "Z")

  2. str_subset(airport_names, "^Red")

  3. str_subset(airport_names, "\\.")

Read and explain what a function is doing

Give a 1 sentence description of what the following function does.

my_function = function(x){
  flights |>
    filter(dest == x) |>
    count() |>
    pull(n)
}

Specify required arguments and default values

Edit my_function so that the default value of x is “MSP”.

my_function = function(x){
  flights |>
    filter(dest == x) |>
    count() |>
    pull(n)
}

Understand how to return a value or object

Explain what the following mystery_function will return. How could you edit the code so it will return mean(flights$dep_delay)?

mystery_function = function(x){
  mean(flights$dep_delay)
  median(flights$dep_delay)
  sd(flights$dep_delay)
}

Use a logical statement to control the flow of the function

Complete the function below called summarize_delays. It takes a vector of numbers x and a string metric.

  • If metric is equal to “mean”, return the mean of x (remove NAs).
  • If metric is equal to “median”, return the median of x (remove NAs).
  • Otherwise, return the string “Metric not supported”.
summarize_delays <- function(x, metric){
  
  if(metric == "mean"){
    
    _______________________
    
    
  } else if (___________) {
    
    _______________________
    
    
  } else {
    
    _______________________
    
  }
}

Use across() and where() to apply {dplyr} functions to columns in a dataset

Write R code that uses across to find the minimum and maximum for each of the quantitative columns in airports.

Be able to read a for loop and determine what it’s doing

The following code chunk creates a vector of some airports in Minnesota.

mn_airports = c("Bemidji Regional Airport", 
                "Brainerd Lakes Regional Airport", 
                "Duluth International Airport", 
                "Ely Municipal Airport", 
                "Redwood Falls Municipal Airport", 
                "Rochester International Airport", 
                "Thief River Falls Regional Airport",
                "Minneapolis-St Paul International/Wold-Chamberlain Airport")
  1. What is the purpose of results = numeric(length(mn_airports)) in the code chunk below?
  2. What does seq_along(mn_airports) do?
  3. What is saved in the x object?
  4. What is saved in the results object?
results = numeric(length(mn_airports))

for(k in seq_along(mn_airports)){
  x <- airports |>
    filter(name == mn_airports[k]) |>
    pull(faa)
  
  results[k] = my_function(x)
}

results
[1]    0    0    0    0    0    0    0 5938

Explain what a map command is doing

I’m attempting to use a map solution instead of my for loop above. Does the map code below accomplish the task? If yes, explain how you can tell. If no, explain what you think the issue is.

map(mn_airports, my_function)
[[1]]
[1] 0

[[2]]
[1] 0

[[3]]
[1] 0

[[4]]
[1] 0

[[5]]
[1] 0

[[6]]
[1] 0

[[7]]
[1] 0

[[8]]
[1] 0