Homework 3

Data Types, Joining Tables, and Data Visualization

Homework 3 questions based on Lectures 6 and 7, with an emphasis on Lecture 7.
Author

Byeong-Hak Choe

Published

October 27, 2026

Homework 3 Question Scores

The table shows the fraction of available points earned on each question, on a 0–1 scale. It combines both sections, using each student’s highest-scoring attempt and recording zero credit for non-submissions.

Instructions

This homework covers Lectures 6 and 7, with more emphasis on Lecture 7. Answer all 36 questions, worth 100 points:

  • Concepts: 50 points. Questions 1–15 are multiple-choice questions; Questions 16–18 are fill-in-the-blank questions.
  • R programming: 50 points. Questions 19–36 each contain one R-code blank.
  • Questions 1–7 and 19–21 focus on Lecture 6. The other 26 questions focus on Lecture 7.

For each multiple-choice question, select the one best answer. For each conceptual blank, enter only the requested term or value. For each coding question, enter only the R code that replaces [?], not the entire code block. Include quotation marks when the missing code is a character string.

A coding blank may require a complete filter condition, aesthetic mapping, or plot layer, rather than just one word. Read the requested result and use the target visualization to check your completed code.

Run the setup code below once, then write and test your answers in an R script. Treat each question as a separate task using the original setup objects. A question does not require you to have completed an earlier question’s code. Chart labels and axis tick formatting are provided for readability and are not assessed; you do not need to add extra formatting code to your answers.

For each question with ggplot() code, a target visualization shows the expected result after filling in the blank. The completed code used to generate that image is not displayed.

All plotted categories use a ggthemes Tableau or colorblind-friendly fill scale. Text labels, panel headings, and legends identify groups so that color is not the only cue.

Use only course materials, R functions, operators, and methods covered in class through Lecture 7. If you are unsure whether a method is allowed, ask before submitting.

Submission: Submit your answers through the Brightspace quiz. Check Brightspace for the due date and attempt limit.

ImportantGenerative AI is not permitted

Complete this homework independently. Do not use generative AI tools to generate, revise, explain, debug, or check your answers or R code. Use the lectures, classwork, and your own course notes. Please ask Prof. Choe if you need help.

Practice Data: Campus Dining Purchases

The following data describe 24 food purchases. One row in purchases represents one purchase, not one unique student. The same student could make more than one purchase, so purchase counts must not be described as counts of students.

locations is a lookup table with one row per listed location. The location codes intentionally appear in a different order from the purchase records. Some codes occur in only one of the two tables.

library(tidyverse)
library(ggthemes)

purchases <- read_csv("https://bcdanl.github.io/data/cafe-purchases.csv")
locations <- read_csv("https://bcdanl.github.io/data/cafe-locations.csv")

If ggthemes is not installed in your R environment, run install.packages("ggthemes") once before running the setup code. The setup uses library(ggthemes) to load it in the current R session.

purchases data.frame

locations data.frame

Variable descriptions

Table Variable Description
purchases purchase_id A numeric identifier for a purchase. The numbers are labels, not amounts or rankings.
Both tables location_code The code used to match a purchase to its dining location.
purchases meal_period The meal period: Lunch or Dinner.
purchases order_method How the purchase was ordered: App or Counter.
purchases wait_minutes Time in minutes from placing the order to receiving it. Zero would mean no waiting.
locations location_name The readable name associated with a listed location code.


Part I: Multiple Choice — Concepts

Question 1

2 points

A dining office stores purchases in a CSV file. Every row uses the same columns, although some cells in an optional notes column are blank. How is this dataset organized?

  1. Unstructured, because at least one cell is blank.
  2. Structured, because the records share a defined row-and-column layout.
  3. Semi-structured, because every CSV file has a different set of fields in each row.
  4. It cannot be classified until the blank cells are replaced with zero.

b. Structured, because the records share a defined row-and-column layout. Blank cells do not remove the shared columns or make the CSV unstructured.

Question 2

2 points

R stores purchase_id as numbers such as 301 and 302. Given the variable description above, which statement is correct?

  1. Purchase 302 represents more food than purchase 301.
  2. The difference between two purchase IDs measures waiting time.
  3. The mean purchase ID summarizes the typical purchase amount.
  4. The IDs are nominal labels, even though R stores them as numbers.

d. The IDs are nominal labels, even though R stores them as numbers. The IDs distinguish purchases. Their numerical order and average do not measure purchase amounts or waiting times.

Question 3

3 points

A dining manager assigns maintenance requests the priorities Low, Medium, and High. Which comparison is justified by these labels alone?

  1. A High-priority request is exactly three times as urgent as a Low-priority request.
  2. The priorities can be ranked, but equal-sized differences between levels are not established.
  3. The priorities have no meaningful order.
  4. Coding the priorities as 1, 2, and 3 proves that every step has the same size.

b. The priorities can be ranked, but equal-sized differences between levels are not established. Low, Medium, and High are ordinal categories. Numerical codes would not prove equal gaps or support “three times as urgent.”

Question 4

3 points

A cafe records refrigerator temperature in degrees Celsius and customer waiting time in minutes. Which statement correctly distinguishes these measurements?

  1. Both are nominal because they are recorded in a table.
  2. A temperature of 10°C is twice as hot as 5°C, but a 10-minute wait is not twice a 5-minute wait.
  3. Waiting time has a meaningful zero and supports ratios; Celsius temperature supports differences but not the same kind of ratio interpretation.
  4. Neither variable supports calculating differences between observations.

c. Waiting time has a meaningful zero and supports ratios; Celsius temperature supports differences but not the same kind of ratio interpretation. A 10-minute wait is twice a 5-minute wait. A temperature of 10°C is not twice as hot as 5°C because 0°C does not mean an absence of temperature.

Question 5

2 points

A table’s rules require a unique purchase_id and a numeric wait_minutes value. Which proposed new record violates both rules?

  1. It reuses an existing purchase ID and records waiting time as the text "five".
  2. It uses a new purchase ID and records waiting time as the number 5.
  3. It uses a new purchase ID and records waiting time as the number 0.
  4. It uses a new purchase ID and the same waiting time as another purchase.

a. It reuses an existing purchase ID and records waiting time as the text "five". Reusing the ID breaks uniqueness, and the text does not satisfy the numeric waiting-time rule. Two different purchases may have the same numeric waiting time.

Question 6

2 points

The dining office uses PostgreSQL to manage stored tables, updates, and access permissions. What role does PostgreSQL play?

  1. It is a database management system (DBMS).
  2. It is a single row in the purchase table.
  3. It is the purchases data frame in the current R session.
  4. It is a measurement scale such as nominal or ratio.

a. It is a database management system (DBMS). PostgreSQL is software that manages stored data, updates, and access. It is not the same thing as one record or an R data frame.

Question 7

3 points

Suppose a left join starts with purchases and adds location_name from locations, matching on location_code. What should happen to purchase 324, whose location code is L9?

  1. The purchase must be deleted because L9 has no matching location record.
  2. The purchase must receive the name from the third row of locations because it is the last purchase.
  3. The purchase remains, and the added location name is NA because no matching lookup record exists.
  4. The purchase remains, and the missing location name becomes the number 0.

c. The purchase remains, and the added location name is NA because no matching lookup record exists. A left join retains the left table’s purchases and matches location codes, not row positions. The missing match does not establish that the purchase has no location.

Question 8

3 points

Use the faceted histograms below. Each panel shows one ordering method, with shared axes and 4-minute bins. Each bin includes its lower endpoint but not its upper endpoint. Across both panels, how many purchases had waits of at least 8 minutes but less than 16 minutes?

Separate App and Counter waiting-time histograms with shared axes and four-minute bins. The App panel has counts 6, 6, 0, and 0; the Counter panel has counts 0, 2, 7, and 3 for the intervals 0 to under 4, 4 to under 8, 8 to under 12, and 12 to under 16 minutes, respectively.

  1. 7 purchases, using only the 8-to-under-12-minute bin.
  2. 10 purchases, adding the counts in the two bins from 8 to under 16 minutes across both panels.
  3. 10 different students, each of whom must have made exactly one purchase.
  4. 18 purchases, adding all bins beginning at 4 minutes or more.

b. 10 purchases, adding the counts in the two bins from 8 to under 16 minutes across both panels. The App panel contributes 0 purchases in these two bins. The Counter panel contributes 7 and 3, so the combined count is 0 + 0 + 7 + 3 = 10. Each panel shows its own ordering method; the observations are purchases, not necessarily different students.

Question 9

3 points

You redraw the histograms in Question 8 using 2-minute bins instead of 4-minute bins, without filtering or changing the data. Which statement is correct?

  1. The dataset now contains twice as many purchase records.
  2. The recorded waiting times change to fit the new bins.
  3. The visible peaks and gaps may change, but the same 24 waiting times are plotted.
  4. The narrower bins guarantee that the population distribution is bimodal.

c. The visible peaks and gaps may change, but the same 24 waiting times are plotted. Changing the bin width changes how observations are grouped in the display, not their recorded values or the number of rows.

Question 10

3 points

Use the boxplots below. Which comparison of the median and the spread of the middle 50% is best supported by these observations?

Boxplots of waiting time by ordering method in the purchase dataset. The App group has a median of 3.5 minutes; the Counter group has a median of 9.5 minutes.

  1. The App group has both a lower median and a narrower interquartile range than the Counter group.
  2. The Counter group has both a lower median and a narrower interquartile range than the App group.
  3. Using the app is proven to cause shorter waiting times for every student.
  4. Each box contains every observed waiting time in its group.

a. The App group has both a lower median and a narrower interquartile range than the Counter group. The medians are 3.5 minutes for App and 9.5 minutes for Counter. The interquartile ranges are 1.5 minutes for App and 3.25 minutes for Counter, so the middle 50% is less spread out for App purchases. The boxes do not contain every observation, and this descriptive comparison does not establish that the app caused shorter waits.

Question 11

3 points

You want all histogram bars to have blue interiors, rather than assigning colors based on a data variable. Which setting expresses this intention?

  1. Put fill = wait_minutes inside aes().
  2. Put color = "steelblue" inside aes() to set the interiors.
  3. Put fill = "steelblue" outside aes(), as an argument to geom_histogram().
  4. Replace wait_minutes with the text "steelblue" in the data frame.

c. Put fill = "steelblue" outside aes(), as an argument to geom_histogram(). This gives every bar the same interior color. An aesthetic mapping inside aes() connects a data variable to a visual feature; color controls the outlines rather than the interiors.

Question 12

3 points

A chart distinguishes two ordering methods using only red and green. Which revision best helps readers who have difficulty distinguishing these colors?

  1. Remove the category labels so readers concentrate on the colors.
  2. Keep the same colors and identify each method only as “the red one” or “the green one.”
  3. Change the underlying purchase counts until the colored groups look more different.
  4. Use a colorblind-friendly palette and retain text labels or labeled panels that identify the groups.

d. Use a colorblind-friendly palette and retain text labels or labeled panels that identify the groups. Readers should be able to identify groups without relying only on red versus green. Improving the design does not require changing the data.

Question 13

3 points

A prepared table has one row per ordering method, with its purchase count already stored in a column named n. You map x = n and y = order_method. Which geometric object directly uses these supplied counts as bar lengths?

  1. geom_histogram()
  2. geom_col()
  3. geom_boxplot()
  4. Default geom_bar(), which automatically treats any column named n as the bar length

b. geom_col(). The prepared table already contains the counts in n, so the bar lengths should use those supplied numbers. Default geom_bar() counts rows instead; it does not automatically use a column just because it is named n.

Question 14

3 points

On another day, one cafe records 200 purchases and another records 50. A manager wants to compare the proportion ordered through the app within each cafe, rather than their total purchase counts. Which chart is most appropriate?

  1. A histogram with cafe names placed into numeric bins.
  2. Side-by-side count bars, interpreted as though counts were already percentages.
  3. A 100% stacked bar chart using position = "fill", with cafe on the x-axis and ordering method mapped to fill.
  4. A boxplot of the cafe identification numbers.

c. A 100% stacked bar chart using position = "fill", with cafe on the x-axis and ordering method mapped to fill. Each cafe’s full bar has height 1. The App segment shows App purchases divided by all purchases at that cafe, allowing comparison of the mix despite different cafe totals. The equal heights do not show the original totals of 200 and 50.

Question 15

3 points

You run purchases |> count(meal_period, order_method). All four meal-period-and-method combinations occur in the setup data. What does one row of the resulting table represent?

  1. One observed combination, such as Lunch and App, with n giving its purchase count.
  2. One student, with n giving that student’s identification number.
  3. One original purchase, with all 24 original rows retained.
  4. One waiting-time bin, with n giving its width in minutes.

a. One observed combination, such as Lunch and App, with n giving its purchase count. count(meal_period, order_method) returns one row per observed pair. Here there are four rows: Lunch/App, Lunch/Counter, Dinner/App, and Dinner/Counter.

Part II: Fill in the Blank — Concepts

Question 16

3 points

A histogram of purchase amounts has two clear peaks separated by a dip. This distribution is described as [?].

Enter the term for its number of peaks, not a direction of skew.

Bimodal

“Bi” refers to two clear peaks. Peak count and direction of skew describe different features.

Question 17

3 points

In a different waiting-time dataset, most purchases have short waits, while a few have very long waits. Its longer tail points toward larger values. The distribution is [?]-skewed.

Enter only left or right.

right

The longer tail extends toward larger values. A right-skewed distribution is also called positively skewed.

Question 18

3 points

The table below describes purchases during lunch on another day, not the 24-row setup dataset.

Meal period Ordering method Number of purchases
Lunch App 12
Lunch Counter 8

These are the only two ordering methods in this table. In a 100% stacked bar for Lunch, the App segment would have a height of [?].

Enter the proportion as a decimal between 0 and 1, not a percentage or the purchase count.

0.6

The App share is

\frac{12}{12 + 8} = \frac{12}{20} = 0.6.

The denominator includes both ordering methods during Lunch in the supplied table. 0.60 is the same numerical answer; 60 would not be a proportion between 0 and 1.

Part III: Fill in the Blank — R Programming

Use the original purchases and locations objects from the setup code. Each question below contains exactly one blank. Run a completed version in your R script before submitting the code that replaces [?].

Question 19

2 points

Add the matching location name to every purchase, including purchases without a matching location record. Fill in the function name.

purchases_with_location <- purchases |>
  [?](locations, by = "location_code")

left_join

purchases_with_location <- purchases |>
  left_join(locations, by = "location_code")

The purchase table is on the left, so every purchase remains. Location names are added where the codes match. Purchase 324 remains with NA for its added location name.

Question 20

2 points

The dining manager now starts with locations to retain every listed location, including Recreation Cafe, which has no purchase in the setup data. Complete the matching-key argument. Match codes, not row positions.

locations_with_purchases <- locations |>
  left_join(purchases, by = [?])

"location_code"

locations_with_purchases <- locations |>
  left_join(purchases, by = "location_code")

The key is supplied as a character string. Because locations is now on the left, Recreation Cafe (L4) remains even without a matching purchase. Its added purchase fields are NA. 'location_code' is also valid.

Question 21

2 points

For the join shown below, each location code occurs at most once in locations. Determine how many rows purchases_with_location will contain, and use that number to complete the assignment.

purchases_with_location <- purchases |>
  left_join(locations, by = "location_code")

expected_rows <- [?]

24

purchases_with_location <- purchases |>
  left_join(locations, by = "location_code")

expected_rows <- 24

All 24 purchases remain. Each code has at most one matching lookup record, so this join does not multiply purchase rows. The unmatched L9 purchase remains; unused lookup code L4 does not create a new purchase row.

Question 22

3 points

Compare the waiting-time distributions for App and Counter in separate panels. Complete the entire aesthetic mapping so waiting time determines horizontal position and ordering method determines the bar interiors.

ggplot(data = purchases,
       mapping = [?]) +
  geom_histogram(binwidth = 3, color = "white", show.legend = FALSE) +
  facet_wrap(~ order_method) +
  scale_fill_tableau()

Target visualization:

Target for Question 22: labeled App and Counter panels show waiting-time histograms with three-minute bins and shared axes. Tableau fills distinguish the two ordering methods.

aes(x = wait_minutes, fill = order_method)

ggplot(data = purchases,
       mapping = aes(x = wait_minutes, fill = order_method)) +
  geom_histogram(binwidth = 3, color = "white", show.legend = FALSE) +
  facet_wrap(~ order_method) +
  scale_fill_tableau()

wait_minutes supplies the numeric horizontal position, and order_method supplies the fill categories. The supplied faceting layer separates App and Counter into labeled panels with shared axes. The histogram counts purchases in each bin.

Question 23

3 points

Show only Lunch purchases with waiting times of at least 4 minutes, then plot their waiting-time distribution. Complete the entire filter condition, combining the two requirements with &.

selected_purchases <- purchases |>
  filter([?])

ggplot(data = selected_purchases,
       mapping = aes(x = wait_minutes)) +
  geom_histogram(binwidth = 2, color = "white", fill = "steelblue") +
  scale_fill_tableau()

Target visualization:

Target for Question 23: a colored histogram of the eight Lunch purchases whose waiting times are at least four minutes, using two-minute bins.

meal_period == "Lunch" & wait_minutes >= 4

selected_purchases <- purchases |>
  filter(meal_period == "Lunch" & wait_minutes >= 4)

ggplot(data = selected_purchases,
       mapping = aes(x = wait_minutes)) +
  geom_histogram(binwidth = 2, color = "white", fill = "steelblue") +
  scale_fill_tableau()

The & requires both conditions to be true for the same purchase. There are 8 matching purchases. The >= retains waits of exactly 4 minutes; using > would incorrectly omit them. Reversing the order of the two conditions gives the same result.

Question 24

3 points

Show waiting times in a separate histogram panel for each ordering method, using 4-minute-wide bins with white outlines. The fill mapping, faceting layer, and palette are already supplied. Complete the entire histogram layer, including the bin-width and outline settings.

ggplot(data = purchases,
       mapping = aes(x = wait_minutes, fill = order_method)) +
  [?] +
  facet_wrap(~ order_method) +
  scale_fill_tableau()

Target visualization:

Target for Question 24: separate App and Counter waiting-time histograms with shared axes, four-minute-wide bins, white outlines, and Tableau fills. Each bar counts purchases only within its ordering-method panel.

geom_histogram(binwidth = 4, color = "white")

ggplot(data = purchases,
       mapping = aes(x = wait_minutes, fill = order_method)) +
  geom_histogram(binwidth = 4, color = "white") +
  facet_wrap(~ order_method) +
  scale_fill_tableau()

The layer bins waiting times into 4-minute intervals and draws white outlines. The supplied facet_wrap(~ order_method) separates App and Counter into panels with shared axes, so the methods are not stacked in the same histogram. Ordering method is mapped to fill, and the Tableau scale sets the interiors. colour = "white" is also valid.

Question 25

3 points

Display the waiting-time distribution in a separate panel for each meal period, using shared axes to support comparison. Complete the entire faceting layer. Keep the original purchases and the same 3-minute bin width.

ggplot(data = purchases,
       mapping = aes(x = wait_minutes, fill = meal_period)) +
  geom_histogram(binwidth = 3, color = "white", show.legend = FALSE) +
  [?] +
  scale_fill_tableau()

Target visualization:

Target for Question 25: separate Dinner and Lunch waiting-time histograms with three-minute bins and shared horizontal and vertical scales.

facet_wrap(~ meal_period)

ggplot(data = purchases,
       mapping = aes(x = wait_minutes, fill = meal_period)) +
  geom_histogram(binwidth = 3, color = "white", show.legend = FALSE) +
  facet_wrap(~ meal_period) +
  scale_fill_tableau()

The complete layer makes one panel per meal period. The default axes are shared, and the bin width stays at 3 minutes in both panels. Supplying only the variable name would not complete the required plot layer.

Question 26

3 points

As an alternative design, let each meal-period panel have its own x-axis range, while keeping a shared y-axis scale. Fill in the character-string argument value discussed in Lecture 7.

ggplot(data = purchases,
       mapping = aes(x = wait_minutes, fill = meal_period)) +
  geom_histogram(binwidth = 3, color = "white", show.legend = FALSE) +
  facet_wrap(~ meal_period, scales = [?]) +
  scale_fill_tableau()

Target visualization:

Target for Question 26: separate Dinner and Lunch histograms with three-minute bins. Each panel has its own waiting-time-axis range, while purchase-count scales remain shared.

"free_x"

ggplot(data = purchases,
       mapping = aes(x = wait_minutes, fill = meal_period)) +
  geom_histogram(binwidth = 3, color = "white", show.legend = FALSE) +
  facet_wrap(~ meal_period, scales = "free_x") +
  scale_fill_tableau()

Each panel may use its own x-axis range, while the y-axis scale remains shared. 'free_x' is also valid. The setting changes the display, not the recorded waits.

Question 27

3 points

Compare waiting times between App and Counter using vertical boxplots. Complete the entire aesthetic mapping: ordering method determines the horizontal categories and box interiors, while waiting time determines vertical position.

ggplot(data = purchases,
       mapping = [?]) +
  geom_boxplot(show.legend = FALSE) +
  scale_fill_tableau()

Target visualization:

Target for Question 27: vertical boxplots of purchase waiting time for App and Counter ordering methods.

aes(x = order_method, y = wait_minutes, fill = order_method)

ggplot(data = purchases,
       mapping = aes(x = order_method,
                     y = wait_minutes,
                     fill = order_method)) +
  geom_boxplot(show.legend = FALSE) +
  scale_fill_tableau()

order_method supplies both the horizontal categories and the box-fill categories. wait_minutes is numeric and supplies vertical position. All three mappings belong inside aes().

Question 28

3 points

Within each meal period, compare the median, quartiles, and spread of waiting time between App and Counter purchases. The panels and mappings are supplied. Choose the geometric-object function that produces the required summaries, rather than histogram bins or category counts.

ggplot(data = purchases,
       mapping = aes(x = order_method, y = wait_minutes,
                     fill = order_method)) +
  [?](show.legend = FALSE) +
  facet_wrap(~ meal_period) +
  scale_fill_tableau()

Target visualization:

Target for Question 28: Dinner and Lunch panels each contain separate App and Counter waiting-time boxplots. A consistent Tableau fill identifies each ordering method across panels.

geom_boxplot

ggplot(data = purchases,
       mapping = aes(x = order_method, y = wait_minutes,
                     fill = order_method)) +
  geom_boxplot(show.legend = FALSE) +
  facet_wrap(~ meal_period) +
  scale_fill_tableau()

Within each labeled meal-period panel, geom_boxplot() summarizes the distribution of waiting time separately for App and Counter. The numeric variable is on the y-axis; histogram bins or category-count bars would answer different questions.

Question 29

3 points

The manager wants to know how many purchases had waits of at least 8 minutes in each meal period. Use the purchase-level records to create horizontal count bars. Complete the filter condition, including waits of exactly 8 minutes.

NotePiping a data frame into ggplot()

my_data |> ggplot(mapping = aes(...)) passes my_data to the first argument, data, of ggplot(). It is equivalent to ggplot(data = my_data, mapping = aes(...)).

purchases |>
  filter([?]) |>
  ggplot(mapping = aes(y = meal_period, fill = meal_period)) +
  geom_bar(show.legend = FALSE) +
  scale_fill_tableau()

Target visualization:

Target for Question 29: horizontal Tableau-colored bars count purchases with waits of at least eight minutes. Dinner has six such purchases and Lunch has four.

wait_minutes >= 8

purchases |>
  filter(wait_minutes >= 8) |>
  ggplot(mapping = aes(y = meal_period, fill = meal_period)) +
  geom_bar(show.legend = FALSE) +
  scale_fill_tableau()

The condition keeps purchases with waits of 8 minutes or longer. geom_bar() then counts those purchase-level rows by meal period: Dinner = 6 and Lunch = 4. The graph compares long-wait purchase counts, not all-purchase totals or counts of unique students.

Question 30

3 points

Create one row for each meal-period-and-ordering-method combination, with the purchase count in n. Fill in the second grouping variable.

meal_method_counts <- purchases |>
  count(meal_period, [?])

Resulting data frame:

meal_period order_method n
Dinner App 4
Dinner Counter 8
Lunch App 8
Lunch Counter 4

order_method

meal_method_counts <- purchases |>
  count(meal_period, order_method)

The resulting data frame is:

meal_period order_method n
Dinner App 4
Dinner Counter 8
Lunch App 8
Lunch Counter 4

The four counts total 24 purchases.

Question 31

3 points

The code below first creates a summary table of purchases with waits of at least 8 minutes by location code. Use its n values to compare long-wait purchase counts across locations. Complete the entire aesthetic mapping for vertical bars: location code determines horizontal position and fill, and the supplied count determines height. Use the codes directly, including L9.

long_wait_counts <- purchases |>
  filter(wait_minutes >= 8) |>
  count(location_code)

ggplot(data = long_wait_counts,
       mapping = [?]) +
  geom_col(show.legend = FALSE) +
  scale_fill_tableau()

Target visualization:

Target for Question 31: vertical Tableau-colored bars use the prepared long-wait purchase counts. L1 has five, L2 has four, and L9 has one purchase with a wait of at least eight minutes.

aes(x = location_code, y = n, fill = location_code)

long_wait_counts <- purchases |>
  filter(wait_minutes >= 8) |>
  count(location_code)

ggplot(data = long_wait_counts,
       mapping = aes(x = location_code, y = n, fill = location_code)) +
  geom_col(show.legend = FALSE) +
  scale_fill_tableau()

The summary counts are L1 = 5, L2 = 4, and L9 = 1. location_code supplies horizontal categories and fill; n supplies bar height. geom_col() uses these prepared counts. Counting rows of this summary would give just one row per location, not the original 5/4/1 purchase counts. Default geom_bar() is not appropriate for the supplied x-and-y mapping.

Question 32

3 points

Use Lunch purchases only to compare ordering-method counts. Order the horizontal bars with the largest count at the top, rather than leaving the categories in alphabetical order. Complete the entire expression for the y-axis category ordering.

lunch_method_counts <- purchases |>
  filter(meal_period == "Lunch") |>
  count(order_method)

ggplot(data = lunch_method_counts,
       mapping = aes(x = n,
                     y = [?],
                     fill = order_method)) +
  geom_col(show.legend = FALSE) +
  scale_fill_tableau()

Target visualization:

Target for Question 32: horizontal Tableau-colored Lunch purchase-count bars are ordered with App at the top, count eight, and Counter below, count four.

fct_reorder(order_method, n)

lunch_method_counts <- purchases |>
  filter(meal_period == "Lunch") |>
  count(order_method)

ggplot(data = lunch_method_counts,
       mapping = aes(x = n,
                     y = fct_reorder(order_method, n),
                     fill = order_method)) +
  geom_col(show.legend = FALSE) +
  scale_fill_tableau()

fct_reorder() uses the supplied Lunch counts to order the y-axis categories. The resulting top-to-bottom order is App (8), then Counter (4). Supplying only order_method would leave the alphabetical category order, placing Counter above App instead of putting the larger count first.

Question 33

3 points

Within each meal period, compare App and Counter purchase counts side by side, with every bar starting at zero. Starting from the original purchase-level rows, complete the entire geometric layer, including the position setting.

ggplot(data = purchases,
       mapping = aes(x = meal_period,
                     fill = order_method)) +
  [?] +
  scale_fill_tableau()

Target visualization:

Target for Question 33: side-by-side purchase-count bars by meal period and ordering method, all starting at zero. Dinner has 4 App and 8 Counter purchases; Lunch has 8 App and 4 Counter purchases.

geom_bar(position = "dodge")

ggplot(data = purchases,
       mapping = aes(x = meal_period,
                     fill = order_method)) +
  geom_bar(position = "dodge") +
  scale_fill_tableau()

The original data have one row per purchase, so geom_bar() counts rows. The "dodge" position places App and Counter side by side within each meal period. Heights remain purchase counts, and every bar starts at zero. Enter the full layer, not just the string "dodge".

Question 34

3 points

Compare the ordering-method proportions within each meal period. Each complete bar should have height 1. Starting from the original purchase-level rows, complete the entire geometric layer, including the position setting that uses each meal period’s total as its denominator.

ggplot(data = purchases,
       mapping = aes(x = meal_period,
                     fill = order_method)) +
  [?] +
  scale_fill_tableau()

Target visualization:

Target for Question 34: each meal-period bar has total height one. App accounts for one-third of Dinner purchases and two-thirds of Lunch purchases.

geom_bar(position = "fill")

ggplot(data = purchases,
       mapping = aes(x = meal_period,
                     fill = order_method)) +
  geom_bar(position = "fill") +
  scale_fill_tableau()

geom_bar() counts the original purchase rows, and position = "fill" rescales each meal-period total to 1. The denominator is the number of purchases in that meal period, not all 24 purchases. App accounts for 4/12 of Dinner purchases and 8/12 of Lunch purchases. Enter the full layer, not just "fill".

Question 35

2 points

A teammate has chosen a scale for point and line colors, but the plot maps ordering method to bar interiors. Supply the complete ggthemes scale call whose name specifically identifies a colorblind-friendly fill palette. It should change the interiors without changing counts or proportions.

ggplot(data = purchases,
       mapping = aes(x = meal_period,
                     fill = order_method)) +
  geom_bar(position = "fill") +
  [?]

Target visualization:

Target for Question 35: within-meal-period proportion bars use a colorblind-friendly black-and-orange fill palette. The legend labels App and Counter directly.

scale_fill_colorblind()

ggplot(data = purchases,
       mapping = aes(x = meal_period,
                     fill = order_method)) +
  geom_bar(position = "fill") +
  scale_fill_colorblind()

The ggthemes function changes the palette for the mapped fill aesthetic. A scale_color_*() function would not change these bar interiors. The counts and within-meal-period proportions stay the same. The blank requires the complete function call, including ().

Question 36

3 points

For purchases with waits of at least 4 minutes, this pipeline first creates one summary row per meal-period-and-ordering-method combination. Complete the entire geometric layer to compare the supplied n values side by side. Choose a layer that uses those counts, rather than counting the summary rows again.

NotePiping a data frame into ggplot()

my_data |> ggplot(mapping = aes(...)) passes my_data to the first argument, data, of ggplot(). It is equivalent to ggplot(data = my_data, mapping = aes(...)). Here, count() produces that input data frame; + then adds the plot layers.

purchases |>
  filter(wait_minutes >= 4) |>
  count(meal_period, order_method) |>
  ggplot(mapping = aes(x = meal_period,
                       y = n,
                       fill = order_method)) +
  [?] +
  scale_fill_tableau()

Target visualization:

Target for Question 36: side-by-side bars use prepared counts of purchases with waits of at least four minutes. Dinner has 2 App and 8 Counter purchases; Lunch has 4 App and 4 Counter purchases.

geom_col(position = "dodge")

The pipe passes the summarized data frame from count() into the data argument of ggplot(). Thus, my_data |> ggplot(mapping = aes(...)) is equivalent to ggplot(data = my_data, mapping = aes(...)). The + operators add plot layers after the data have been supplied.

purchases |>
  filter(wait_minutes >= 4) |>
  count(meal_period, order_method) |>
  ggplot(mapping = aes(x = meal_period,
                       y = n,
                       fill = order_method)) +
  geom_col(position = "dodge") +
  scale_fill_tableau()

The filtered data contain 18 purchases. The count table has four summary rows: Dinner/App = 2, Dinner/Counter = 8, Lunch/App = 4, and Lunch/Counter = 4. geom_col() uses those n values, while "dodge" puts the methods side by side. In contrast, default geom_bar() counts rows and does not use n as a supplied bar height. Question 33 counts the original purchase-level records automatically; this question first filters the records and then plots prepared counts.

Back to top