Course intro & what is R?

Day 1 - Monday, May 18, 2026

Introductions

Instructor: Charles Costanzo

  • Statistics Ph.D. student
  • Hometown: Solon, OH
  • Some of my favorite things: cats, coffee, R (unironically)

Solon, Ohio

Show the R code.
# Install these first if you don't have them:
# install.packages(c("sf", "tigris"))
library(ggplot2)
library(sf)
library(tigris)
library(dplyr)

options(tigris_use_cache = TRUE)

# Fetch spatial data
ohio_counties <- counties(state = "OH", cb = TRUE, progress_bar = FALSE)
ohio_places <- places(state = "OH", cb = TRUE, progress_bar = FALSE)

# Isolate areas
cuyahoga_county <- ohio_counties %>% filter(NAME == "Cuyahoga")
solon_city <- ohio_places %>% filter(NAME == "Solon")

# Build the map
ggplot() +
  geom_sf(data = ohio_counties,
          fill = "#f8f9fa", color = "grey", linewidth = 0.3) +
  geom_sf(data = cuyahoga_county,
          fill = "#D6EAF8", color = "#2980B9", linewidth = 0.5) +
  geom_sf(data = solon_city,
          fill = "dodgerblue", color = "darkblue", linewidth = 0.5) +
  geom_sf_text(data = solon_city, aes(label = NAME),
               size = 5, fontface = "bold", color = "dodgerblue",
               nudge_y = -0.05, nudge_x = 0.25) +
  theme_void()

Map of Ohio with all counties outlined in light gray. Cuyahoga County in the northeast is shaded light blue, and within it the city of Solon is shaded dark blue with a labeled marker. The map highlights Solon's location in northeastern Ohio.

Meet My Cats!

A fluffy black cat named Babuh sitting calmly and looking at the camera.

Babuh

A brown tabby cat named Tartarus lounging contentedly.

Tartarus

More Realistic Cat Photos…

Babuh the gray cat in a bathtub, fur wet and flattened, looking distinctly unhappy.

Babuh in the bathtub looking soaked and indignant.

Babuh the gray cat being lathered with shampoo during a bath, looking miserable.

Babuh mid-bath, fur fully soaked.

Babuh the gray cat wrapped in a towel after the bath, fur damp and disheveled.

Babuh wrapped in a towel after the bath.

Countries I’ve Been To

Show the R code.
library(ggplot2)
library(maps)
library(dplyr)

world_map <- map_data("world")

visited_countries <- c("Canada", "USA", "Argentina", "Uruguay",
                       "Switzerland", "Rwanda", "Spain", "France", "Turkey")

world_map <- world_map %>%
  mutate(visited = ifelse(region %in% visited_countries, "Visited", "Not Visited"))

ggplot(world_map, aes(x = long, y = lat, group = group, fill = visited)) +
  geom_polygon(color = "white", linewidth = 0.2) +
  scale_fill_manual(values = c("Not Visited" = "#e0e0e0", "Visited" = "#FF7F50")) +
  theme_void() +
  theme(legend.position = "none")

World map with countries the instructor has visited shaded in coral orange and other countries in light gray. Visited countries are Canada, USA, Argentina, Uruguay, Switzerland, Rwanda, Spain, France, and Turkey, spanning North America, South America, Europe, and East Africa.

States I’ve Lived In & Visited

Show the R code.
# Note: install.packages("mapproj") if needed
library(ggplot2)
library(maps)
library(dplyr)
library(mapproj)

us_map <- map_data("state")

lived_in <- tolower(c("Ohio", "Pennsylvania", "Texas"))

# Note: "District of Columbia" matches the map data; "Washington DC" wouldn't
visited <- tolower(c("Washington", "Oregon", "California", "Nevada", "Idaho",
                     "Montana", "Arizona", "New Mexico", "Colorado", "Wyoming",
                     "North Dakota", "South Dakota", "Kansas", "Iowa",
                     "Nebraska", "Minnesota", "Wisconsin", "Michigan", "Indiana",
                     "Illinois", "Kentucky", "Tennessee", "Louisiana", "Florida",
                     "Georgia", "North Carolina", "South Carolina", "Virginia",
                     "District of Columbia", "Maryland", "Delaware", "New Jersey",
                     "New York", "Missouri", "Utah", "West Virginia"))

us_map <- us_map %>%
  mutate(status = case_when(
    region %in% lived_in ~ "Lived",
    region %in% visited ~ "Visited",
    TRUE ~ "Not Visited"
  )) %>%
  mutate(status = factor(status, levels = c("Lived", "Visited", "Not Visited")))

ggplot(us_map, aes(x = long, y = lat, group = group, fill = status)) +
  geom_polygon(color = "white", linewidth = 0.3) +
  scale_fill_manual(values = c("Lived" = "#2C3E50",
                               "Visited" = "#3498DB",
                               "Not Visited" = "#E0E0E0")) +
  coord_map("albers", lat0 = 39, lat1 = 45) +
  theme_void() +
  theme(legend.position = "bottom",
        legend.title = element_blank(),
        legend.text = element_text(size = 14))

Map of the continental United States with three categories. States lived in (Ohio, Pennsylvania, Texas) are shaded dark navy blue. States visited (many states across the West, Midwest, South, and Northeast plus DC) are shaded medium blue. Remaining states are light gray. Legend at the bottom labels Lived, Visited, and Not Visited.

Icebreaker 🧊: Share Your…

  • Name
  • Major
  • Programming Experience
  • A Fun Fact (Favorite Song, Color, Food, etc.)

NoteToday: Monday May 18

Before class

Plan for today

  • Course logistics
  • Introduction to R and RStudio
  • Tidy data
  • R Demo

Helpful links

Course logistics

Course Info

Summer Session 1: May 18, 2026 – June 26, 2026

  • Class time: M/T/W/Th/F, 9:35 a.m. to 10:50 a.m.

  • Class location: Huck Life Sciences Building 007

  • Instructor: Charles Costanzo

    • Email: cgc5478@psu.edu
    • Office Hours: M/W/Th/F: 10:50-11:50 a.m. in Huck 005 (or on Zoom by appt)
  • Teaching Assistant (TA): Xinyue Wang

Learning Goals

This course will teach you how to:

  • Use R: Program in the R language effectively and use the R software environment to efficiently compute with data.
  • Wrangle Real Data: Access, clean, join, and format data from various sources.
  • Visualize Information: Create graphical and descriptive summaries of data.
  • Build Reproducible Workflows: Write well-documented code using tools like RStudio, RMarkdown, and Git/GitHub.
TipNo previous programming background is required for this course.
ImportantThis is not a course on general purpose programming.

Course logistics

  • Six weeks is short. Daily pace is faster than a 15-week course. Falling a week—or even a day—behind is more serious than spring/fall courses.
  • Attendance matters. Lots of in-class graded work (activities, quizzes, oral checkpoints).
  • Timely communication is critical. Reach out to me as soon as possible if something comes up that necessitates you missing class, having a deadline extended, etc.
Assignment weights
Readings Quizzes In-class activities Homework Exam Course project
10% 15% 25% 10% 20% 20%
Grading scheme
A A- B+ B B- C+ C D F
93% 90% 87% 83% 80% 77% 70% 60% below 60%

AI policy

  • Open assessments (Homework & Project): AI tools are permitted with mandatory disclosure.
  • Closed-book, in-person work (Quizzes, Exam, Activities, Oral Checkpoints): AI tools are strictly prohibited.
  • Disclosure is graded (1-2 points).
  • You must be able to explain any code you submit, which I will verify during in-class oral project checkpoints.
  • Roughly 60% of your grade comes from verified in-person work where AI cannot be used.

Course Readings (Perusall)

  • All assigned textbook readings are hosted on Perusall, a collaborative e-reading platform.
  • How grading works: You earn credit through holistic engagement (reading the entire text, spending active time, leaving high-quality comments, and replying to classmates).
  • No access code needed! You must access readings directly through Canvas links to automatically authenticate your Penn State account.
ImportantLet’s try it together right now:
  1. Log into our Canvas course.
  2. Click the “Perusall” tab on the left.
  3. Click the link for DC Section 1 (§1.1–1.5).

What is R?

What is R?

R is a programming language and a software environment for statistical computing and graphics.

  • Designed by statisticians for the purpose of data analysis.
  • First version created in August 1993 (almost 33 years ago).
  • Has grown rapidly in popularity and is widely used in academia and industry by statisticians, data analysts, and data scientists alike.
  • Enormous number of user-contributed packages, which are add-ons that extend the functionality of R.
    • Currently the Comprehensive R Archive Network (CRAN) package repository features 23,664 available packages.1

Some Examples of Said R Packages

A grid of dozens of hexagonal stickers, each representing a different R package such as ggplot2, dplyr, tidyr, shiny, knitr, and others. The hex stickers are tiled together into a colorful honeycomb pattern.

A grid of dozens of hexagonal stickers, each representing a different R package such as ggplot2, dplyr, tidyr, shiny, knitr, and others. The hex stickers are tiled together into a colorful honeycomb pattern.

Hex stickers from the rstudio/hex-stickers repository.

R vs. RStudio

  • R is a computer language that performs computations based on human-written instructions.
  • RStudio is an integrated development environment (IDE) for R programming. It combines the R console with supplementary tools for more efficient R programming.

The R programming language logo: a stylized capital letter R in blue, set inside a gray oval ring.

R: Do not open this

 

The RStudio logo: the word RStudio in dark text next to a light blue hexagonal icon containing a stylized R.

RStudio: Open this

Tidy data

Tidy Data \(\neq\) Neat Data

TipThis table is easy for humans to read. What might make it tricky for a computer to read?

Screenshot of a Pennsylvania Department of State spreadsheet showing voter party-change applications by county. The layout uses multi-row merged header cells that group columns under 'This week' and 'Year to date', with sub-headers splitting each group into Democratic and Republican target parties, and further sub-headers for origin party (Republican or Other / Democratic or Other). County names run down the leftmost column. This nested-header structure is readable for humans but difficult for software to parse as a flat data table.

A spreadsheet showing party change applications in PA. Source: PA Dept. of State (May 4–11, 2026).

Two simple rules for Tidy Data:

  1. Consistent Cases (Rows): Each row must represent a single, distinct instance of your unit of observation.
  2. Uniform Variables (Columns): Every column contains the same type of value.

PA Voter Table - Tidied Up

Show the R code.
# 1. Load data and provide clean column names to handle the nested headers
raw_data <- readxl::read_excel("data/currentvotestats.xlsx",
                       sheet = "Party-to-Party(2026)",
                       skip = 3, # Skip the human-readable headers
                       col_names = c("county",
                                     "week_dem_R", "week_dem_OTH",
                                     "week_rep_D", "week_rep_OTH",
                                     "year_dem_R", "year_dem_OTH",
                                     "year_rep_D", "year_rep_OTH"))

# 2. Clean and Pivot
tidy_voter_data <- raw_data %>%
  filter(!is.na(county), county != "Totals:") %>%
  pivot_longer(
    cols = -county,
    names_to = c("period", "target_party", "origin_party"),
    names_sep = "_",
    values_to = "count"
  )

knitr::kable(
  head(tidy_voter_data %>% filter(county == "CENTRE")),
  caption = "First six rows of the tidied PA voter party-change data, filtered to Centre County. Each row is one combination of period, target party, and origin party with its corresponding count."
)
First six rows of the tidied PA voter party-change data, filtered to Centre County. Each row is one combination of period, target party, and origin party with its corresponding count.
county period target_party origin_party count
CENTRE week dem R 2
CENTRE week dem OTH 14
CENTRE week rep D 3
CENTRE week rep OTH 4
CENTRE year dem R 88
CENTRE year dem OTH 130

Demos

Demo: what R can do

Show the R code.
library(tidyverse)
library(palmerpenguins)

Attaching package: 'palmerpenguins'
The following objects are masked from 'package:datasets':

    penguins, penguins_raw
Show the R code.
# What does the data look like?
glimpse(penguins)
Rows: 344
Columns: 8
$ species           <fct> Adelie, Adelie, Adelie, Adelie, Adelie, Adelie, Adel…
$ island            <fct> Torgersen, Torgersen, Torgersen, Torgersen, Torgerse…
$ bill_length_mm    <dbl> 39.1, 39.5, 40.3, NA, 36.7, 39.3, 38.9, 39.2, 34.1, …
$ bill_depth_mm     <dbl> 18.7, 17.4, 18.0, NA, 19.3, 20.6, 17.8, 19.6, 18.1, …
$ flipper_length_mm <int> 181, 186, 195, NA, 193, 190, 181, 195, 193, 190, 186…
$ body_mass_g       <int> 3750, 3800, 3250, NA, 3450, 3650, 3625, 4675, 3475, …
$ sex               <fct> male, female, female, NA, female, male, female, male…
$ year              <int> 2007, 2007, 2007, 2007, 2007, 2007, 2007, 2007, 2007…
Show the R code.
# Quick summary by species
penguins |>
  group_by(species) |>
  summarize(
    n            = n(),
    mean_mass_g  = mean(body_mass_g,    na.rm = TRUE),
    mean_bill_mm = mean(bill_length_mm, na.rm = TRUE)
  )
# A tibble: 3 × 4
  species       n mean_mass_g mean_bill_mm
  <fct>     <int>       <dbl>        <dbl>
1 Adelie      152       3701.         38.8
2 Chinstrap    68       3733.         48.8
3 Gentoo      124       5076.         47.5
Show the R code.
# A nice plot
penguins |>
  ggplot(aes(x = bill_length_mm, y = body_mass_g, color = species)) +
  geom_point(alpha = 0.7) +
  geom_smooth(method = "lm", se = FALSE) +
  labs(
    title = "Bill length vs body mass, by species",
    x = "Bill length (mm)",
    y = "Body mass (g)"
  ) +
  theme_minimal()
`geom_smooth()` using formula = 'y ~ x'
Warning: Removed 2 rows containing non-finite outside the scale range
(`stat_smooth()`).
Warning: Removed 2 rows containing missing values or values outside the scale range
(`geom_point()`).

Scatter plot of bill length in millimeters on the x-axis versus body mass in grams on the y-axis for three penguin species: Adelie, Chinstrap, and Gentoo. Each species is plotted in a different color with a linear best-fit line. Gentoo penguins cluster at the top right (longer bills, heavier bodies); Adelie penguins cluster at the bottom left (shorter bills, lighter bodies); Chinstrap penguins fall in between with longer bills but moderate body mass.

Demo: a campus map

Show the interactive Leaflet code.
library(tidyverse)
library(sf)
library(tigris)
library(leaflet)

# 1. Centre County boundary, reprojected for Leaflet (WGS84 / CRS 4326)
options(tigris_use_cache = TRUE)
centre_county <- counties(state = "PA", cb = TRUE, progress_bar = FALSE) |>
  filter(NAME == "Centre") |>
  st_transform(4326)
Retrieving data for the year 2024
Show the interactive Leaflet code.
# 2. Huck Life Sciences Building
huck_building <- tibble(
  lon = -77.86146,
  lat = 40.80100,
  name = "Huck Life Sciences Building"
) |>
  st_as_sf(coords = c("lon", "lat"), crs = 4326)

# 3. Build the map
leaflet() |>
  addProviderTiles(providers$Esri.WorldImagery) |>
  addPolygons(
    data = centre_county,
    fillColor = "#041E42",
    fillOpacity = 0.1,
    color = "#FFF",
    weight = 3,
    dashArray = "5, 5"
  ) |>
  addCircleMarkers(
    data = huck_building,
    color = "#FFFFFF",
    weight = 1,
    fillColor = "#0096FF",
    radius = 8,
    fillOpacity = 0.9,
    label = ~name,
    labelOptions = labelOptions(
      style = list(
        "font-family" = "Arial, sans-serif",
        "font-weight" = "bold",
        "color" = "#041E42",
        "padding" = "4px 8px"
      ),
      direction = "auto"
    ),
    popup = "<b>Huck Life Sciences</b><br>Class meets in Room 007"
  )

Setup checklist — due by Wednesday

Install R and RStudio

WarningMac users

Install XQuartz too — some packages we’ll use later in the course need it.

Configure RStudio

  • Tools > Global Options... > General
  • Restore .RData into workspace at startup: Unchecked
  • Save workspace to .RData on exit: Never

Assignments due Wednesday 5/20

Wrap-up & looking ahead

Tomorrow: A tour of RStudio, R as a calculator, and creating your first objects

Upcoming Deadlines

Reach out

Stuck? Office hours, or email me (cgc5478@psu.edu) or Xinyue (xpw5228@psu.edu).

Reference

Syllabus · AI policy · Schedule · Data Computing