Appendix E — Project Title: A Short, Specific Question

Project group Group name
Student 1 Full Name (UT EID: abc123)
Student 2 Full Name (UT EID: xyz789)
  1. Download this file (final_project_template.qmd) and save it in a new folder for your project. Open it in RStudio and click Render to check that the course setup works.
  2. Put your data files in a data/ folder and your screenshots in an images/ folder, both next to this file.
  3. Foreground the wrangling, not the analysis. Explain your challenges and “show your working”: show your data at each step, so a reader can see what each step changed.
  4. The workflow is organized by steps of your workflow, not by framework. Each step has a short explanation, then tabs showing that step in R tidyverse, Python pandas, DuckDB SQL, and Excel Power Query. Click a tab and all the tabsets switch to that framework.
  5. Steps don’t have to line up perfectly across frameworks. Some steps happen in only one framework (see Step 1), and sometimes one framework does two steps at once (see the Excel tabs in Steps 3 and 4). Say so in the tab rather than leaving it empty.
  6. Everything marked Example Remove: is a tiny made-up example (stores, state names, and state populations). Replace it with your own steps, data, and code. Also remove the instructions in italics as you replace them with your own writing.
  7. Check the layout of your Python code against the PEP 8 style guide.
  8. Make your HTML file with the Render button in RStudio (for .qmd files Render replaces the older Knit button, which is for .Rmd files). Render runs all your code from the start in a fresh session, so the HTML shows exactly what your code does; don’t export or print from the Viewer. Submit the single HTML file that Render produces, which is saved next to this file. The embed-resources: true line in the header puts your screenshots inside that file; don’t remove it.
  9. Before submitting, test that your screenshots really are inside the HTML file: email just the .html file to your partner (or to yourself on another computer) and open it from the email. If every screenshot shows, it’s ready. Opening it on your own computer isn’t a good test, because the browser can find the images in your images/ folder even when they aren’t in the file.

Course setup

These chunks check your software versions and load the packages. Leave them as they are.

Course setup (R): check versions and load packages
# Checks that R and each package are installed and new enough for this course.
# Stops with a list of everything that needs fixing, and how to fix it.
check_course_versions <- function(required, area) {
  problems <- character(0)
  to_install <- character(0)
  found <- character(0)
  for (name in names(required)) {
    need <- required[[name]]
    if (name == "R") {
      have <- getRversion()
      if (have < need) {
        problems <- c(problems, sprintf(
          "R is version %s; this course needs %s or newer. Install the current R from https://cran.r-project.org/ (see https://howisonlab.github.io/datawrangling/current/rtidyverse/rstudio_installation.html), then reinstall your packages.",
          have, need))
      }
      found <- c(found, paste("R", have))
    } else if (!nzchar(system.file(package = name))) {
      problems <- c(problems, sprintf("%s is not installed.", name))
      to_install <- c(to_install, name)
    } else {
      have <- packageVersion(name)
      if (have < need) {
        problems <- c(problems, sprintf(
          "%s is version %s; this course needs %s or newer.", name, have, need))
        to_install <- c(to_install, name)
      } else if (isNamespaceLoaded(name) && getNamespaceVersion(name) != have) {
        problems <- c(problems, sprintf(
          "%s %s is installed, but this R session is still using %s. Restart R.",
          name, have, getNamespaceVersion(name)))
      }
      found <- c(found, paste(name, have))
    }
  }
  if (length(problems) > 0) {
    fix <- "In RStudio choose Session > Restart R"
    if (length(to_install) > 0) {
      fix <- paste0(fix, ", then run this in the Console:\n  install.packages(c(",
                    paste0('"', to_install, '"', collapse = ", "), "))\n")
    }
    stop("Course setup (", area, ") found problems:\n  - ",
         paste(problems, collapse = "\n  - "), "\n\n",
         fix, "\nThen run the setup chunk(s) again.", call. = FALSE)
  }
  cat("Course setup OK (", area, "): ", paste(found, collapse = ", "), "\n", sep = "")
}

check_course_versions(c(
  R = "4.5.0",         # CRAN builds Mac/Windows packages for the current and previous R only
  tidyverse = "2.0.0",
  dplyr = "1.2.0",     # recode_values() and replace_values()
  tidyr = "1.3.0",     # separate_wider_delim()
  gt = "1.0.0",        # needed by gtExtras
  gtExtras = "0.6.1"   # works with ggplot2 4
), "R")

library(tidyverse)
library(gt)
library(gtExtras)
Course setup OK (R): R 4.6.1, tidyverse 2.0.0, dplyr 1.2.1, tidyr 1.3.2, gt 1.3.0, gtExtras 0.6.2
Course setup (Python): check reticulate and choose Python packages
# needs check_course_versions() from the Course setup (R) chunk
check_course_versions(c(
  reticulate = "1.41.0"  # py_require()
), "Python")

library(reticulate)
# reticulate sets up a Python with these packages for us (the first run downloads them).
# This must run before any python chunk: if Python has already started, restart R first.
py_require(c(
  "pandas>=3.0",         # pd.col() in assign
  "numpy",
  "pyjanitor"            # clean_names() for snake_case column names
), python_version = ">=3.11")
Course setup OK (Python): reticulate 1.46.0
Course setup (Python): import packages
import sys
import pandas as pd
import numpy as np
import janitor
from io import StringIO

print("Course setup OK (Python): Python", sys.version.split()[0], "pandas", pd.__version__)
Course setup OK (Python): Python 3.12.13 pandas 3.1.1
Course setup (SQL): check versions and connect to DuckDB
# needs check_course_versions() from the Course setup (R) chunk
check_course_versions(c(
  DBI = "1.0.0",
  duckdb = "1.5.5"     # duckdb(shared_home = FALSE)
), "SQL")

library(DBI)
library(duckdb)
options(duckdb.enable_rstudio_connection_pane = TRUE)

# a temporary in-memory database, nothing saved to a file
drv <- duckdb(shared_home = FALSE)
con <- dbConnect(drv)
Course setup OK (SQL): DBI 1.3.0, duckdb 1.5.6

Project packages

Don’t edit the course setup chunks above. If your project needs other packages (for example a graphing library you are learning yourself), add them in the chunks below.

  • R: add library() lines to the R chunk. Install a new package once, in the Console, with install.packages("packagename").
  • Python: add the package name to py_require() in the R chunk (reticulate installs it for you), then add the import line to the Python chunk.

The example uses matplotlib to graph the Python results. If you don’t need any extra packages, delete this section.

py_require("matplotlib")
import matplotlib.pyplot as plt

Project description

Your project description paragraph, updated from the earlier assignment: what question does your project answer, and what makes the wrangling interesting?

Example Remove: Which state has more taco and burrito stores per person, Texas or California? The challenge is that the stores data writes state names many different ways, so we have to resolve those synonyms before we can join to population data.

Data sources

One row per dataset. Show how you meet the requirement of at least three datasets from at least two different organizations.

Example Remove:

Dataset Organization Link Format What is one row?
stores.csv Example Org A https://example.org/stores csv one store
state_synonyms.csv Made by us (this project) csv one way of writing a state’s name
state_population.csv Example Org B https://example.org/population csv one state

Then, for each dataset, a short subsection with a readable screenshot showing the headers and a few rows of data, and the issues you had to manage in reading it (extra header rows, odd encodings, numbers stored as text, footnotes, and so on). Highlight what has synonyms in your data.

Example Remove: stores.csv (Example Org A)

The state column writes the same state in different ways (“Texas”, “TX”, “Tejas”). These are our synonyms; we made state_synonyms.csv to map each way of writing a state to its two-letter code.

  1. Take the screenshot. Mac: Cmd-Shift-4, then drag to select an area. Windows: Windows-Shift-S, then save the image from the notification.
  2. Make it readable: zoom in before taking it, and crop it to the part that matters. For data, show the header row and a few rows. For Excel, show the Power Query Applied Steps pane or the formula bar when those explain what you did.
  3. Save it in the images/ folder next to this file with a descriptive name, e.g., images/stores_csv.png. Avoid spaces in file names.
  4. Include it with a line like this, where the text in the square brackets describes what the screenshot shows:
![stores.csv opened in a text editor, showing the header row and the first five stores](images/stores_csv.png){width=80%}
  1. Render and check that the image appears. If it doesn’t, check the file name and folder (they must match exactly, including capital letters). Before submitting, test the HTML file on another computer (see step 9 in “How to use this template”).

In this template the screenshot lines are inside <!-- --> comments so it renders without the images. Remove the <!-- and --> once your screenshot is saved.

Data model (optional)

If it helps explain your project, show how your tables relate and which columns you join on. A photographed sketch included as a screenshot is fine.

Workflow

Your project, implemented start to finish in each of the four frameworks. Each step starts with a short explanation of what the step does and why, written once for all frameworks. The tabs then show the code (or, for Excel Power Query, the steps and screenshots) and the data after the step. Rename, add, and remove steps to fit your project.

Example Remove: Step 1: Get the data

Explain where each file comes from and how you got it. This step only happens in R, so it has no tabs: the R code saves the data files that every framework then reads. (In your project this step might be downloading files with download.file(), or just a sentence saying you downloaded them by hand.)

dir.create("data", showWarnings = FALSE)

write_csv(tribble(
  ~store_name,     ~state,
  "Taco Hut",      "Texas",
  "Taco Hut 2",    "TX",
  "Burrito Barn",  "Tejas",
  "Bean Shack",    "California",
  "Bean Shack 2",  "Calif.",
  "Burrito Barn 2", "CA"
), "data/stores.csv")

write_csv(tribble(
  ~state_variant, ~state_code,
  "Texas",        "TX",
  "TX",           "TX",
  "Tejas",        "TX",
  "California",   "CA",
  "CA",           "CA",
  "Calif.",       "CA"
), "data/state_synonyms.csv")

write_csv(tribble(
  ~state_code, ~population,
  "TX",        31000000,
  "CA",        39000000
), "data/state_population.csv")

Example Remove: Step 2: Read the data

Explain what you are reading and anything tricky about it (headers, encodings, skipped rows).

stores <- read_csv("data/stores.csv")
state_synonyms <- read_csv("data/state_synonyms.csv")
state_population <- read_csv("data/state_population.csv")

stores
stores = pd.read_csv("data/stores.csv")
state_synonyms = pd.read_csv("data/state_synonyms.csv")
state_population = pd.read_csv("data/state_population.csv")

stores
       store_name       state
0        Taco Hut       Texas
1      Taco Hut 2          TX
2    Burrito Barn       Tejas
3      Bean Shack  California
4    Bean Shack 2      Calif.
5  Burrito Barn 2          CA
CREATE OR REPLACE TABLE stores AS SELECT * FROM 'data/stores.csv';
CREATE OR REPLACE TABLE state_synonyms AS SELECT * FROM 'data/state_synonyms.csv';
CREATE OR REPLACE TABLE state_population AS SELECT * FROM 'data/state_population.csv';
SELECT * FROM stores
6 records
store_name state
Taco Hut Texas
Taco Hut 2 TX
Burrito Barn Tejas
Bean Shack California
Bean Shack 2 Calif.
Burrito Barn 2 CA
  1. For each file: Data > Get Data > From File > From Text/CSV, then Transform Data to open it in the Power Query Editor.
  2. Checked that Power Query used the first row as headers and guessed the column types correctly.

Example Remove: Step 3: Handle synonyms

Explain the synonym problem and how your code resolves it. Show a check that nothing was left unmatched.

stores_clean <- stores %>%
  left_join(state_synonyms, join_by(state == state_variant))

stores_clean
# check: any stores whose state didn't match a synonym?
stores_clean %>%
  filter(is.na(state_code))
stores_clean = (
    stores
    .merge(state_synonyms, how="left",
           left_on="state", right_on="state_variant")
)

stores_clean
       store_name       state state_variant state_code
0        Taco Hut       Texas         Texas         TX
1      Taco Hut 2          TX            TX         TX
2    Burrito Barn       Tejas         Tejas         TX
3      Bean Shack  California    California         CA
4    Bean Shack 2      Calif.        Calif.         CA
5  Burrito Barn 2          CA            CA         CA
# check: any stores whose state didn't match a synonym?
stores_clean[stores_clean["state_code"].isna()]
Empty DataFrame
Columns: [store_name, state, state_variant, state_code]
Index: []
CREATE OR REPLACE TABLE stores_clean AS
SELECT stores.store_name, stores.state, state_synonyms.state_code
FROM stores
  LEFT JOIN state_synonyms ON stores.state = state_synonyms.state_variant;
SELECT * FROM stores_clean
6 records
store_name state state_code
Taco Hut Texas TX
Taco Hut 2 TX TX
Burrito Barn Tejas TX
Bean Shack California CA
Bean Shack 2 Calif. CA
Burrito Barn 2 CA CA
-- check: any stores whose state didn't match a synonym?
SELECT * FROM stores_clean WHERE state_code IS NULL
0 records
store_name state state_code

In Power Query we handled synonyms and the population join together in one query. See the Excel Power Query tab in Step 4.

Example Remove: Step 4: Join population and calculate stores per million people

Explain the join, the aggregation, and the calculation.

stores_per_state <- stores_clean %>%
  group_by(state_code) %>%
  summarize(num_stores = n()) %>%
  left_join(state_population, join_by(state_code)) %>%
  mutate(stores_per_million = num_stores / population * 1000000)

stores_per_state
stores_per_state = (
    stores_clean
    .groupby("state_code", as_index=False)
    .agg(num_stores=("store_name", "count"))
    .merge(state_population, on="state_code", how="left")
    .assign(stores_per_million=(
        pd.col("num_stores") / pd.col("population") * 1000000
    ))
)

stores_per_state
  state_code  num_stores  population  stores_per_million
0         CA           3    39000000            0.076923
1         TX           3    31000000            0.096774
CREATE OR REPLACE TABLE stores_per_state AS
SELECT stores_clean.state_code,
       COUNT(*) AS num_stores,
       state_population.population,
       COUNT(*) / state_population.population * 1000000 AS stores_per_million
FROM stores_clean
  LEFT JOIN state_population ON stores_clean.state_code = state_population.state_code
GROUP BY stores_clean.state_code, state_population.population;
SELECT * FROM stores_per_state
2 records
state_code num_stores population stores_per_million
TX 3 3.1e+07 0.0967742
CA 3 3.9e+07 0.0769231

This tab covers Steps 3 and 4 together. Describe what you did, step by step, e.g.:

  1. In the stores query, Home > Merge Queries with state_synonyms, matching state to state_variant (Left Outer join), then expanded the state_code column.
  2. Filtered state_code for null to check that every store matched, then removed the filter.
  3. Transform > Group By state_code, with a new column num_stores that counts rows.
  4. Home > Merge Queries with state_population on state_code, then expanded population.
  5. Add Column > Custom Column stores_per_million with the formula [num_stores] / [population] * 1000000.

Example Remove: Step 5: Analysis output

The output of your analysis (graph, map, or statistical test), in each framework. Keep this short: if you did several analyses, include only the one or two that best tell your story.

ggplot(stores_per_state, aes(x = state_code, y = stores_per_million)) +
  geom_col(fill = "#66c2a5") +
  labs(x = "State", y = "Stores per million people")

ax = stores_per_state.plot.bar(
    x="state_code", y="stores_per_million", color="#66c2a5", legend=False
)
ax.set_xlabel("State")
ax.set_ylabel("Stores per million people")
plt.show()

SQL doesn’t draw graphs, so we save the query result into an R data frame (output.var) and graph it with ggplot.

SELECT * FROM stores_per_state
ggplot(stores_per_state_sql, aes(x = state_code, y = stores_per_million)) +
  geom_col(fill = "#66c2a5") +
  labs(x = "State", y = "Stores per million people")

  1. Home > Close & Load To… a table on a new sheet.
  2. Selected the table and chose Insert > Column Chart.

Results

A few sentences on what your output shows. Do your four versions give the same numbers? If not, explain why.

For a results table, pass a data frame to gt() rather than printing it raw: give it a title, readable column labels, and formatted numbers.

Example Remove:

stores_per_state %>%
  gt() %>%
  tab_header(
    title = "Taco and burrito stores per million people",
    subtitle = "Texas and California"
  ) %>%
  cols_label(
    state_code = "State",
    num_stores = "Stores",
    population = "Population",
    stores_per_million = "Stores per million"
  ) %>%
  fmt_integer(population) %>%
  fmt_number(stores_per_million, decimals = 2) %>%
  tab_source_note("Source: example data made up for this template.")
Taco and burrito stores per million people
Texas and California
State Stores Population Stores per million
CA 3 39,000,000 0.08
TX 3 31,000,000 0.10
Source: example data made up for this template.

A challenge we are proud to have solved

Describe one challenge you resolved that you are particularly proud of: what went wrong, what you tried, and what finally worked. Show the data before and after.

Learning new tools

A few paragraphs reflecting on how you learned tools that you taught yourselves for this project (for example a graphing library): where you looked, what was hard, and what helped.