An introduction to R's core data structures through applied exploration of real datasets, using AI-assisted prompting
Working effectively with an AI model depends on the same discipline regardless of the task: supplying a role, a task, context, and a format, and then verifying the output before relying on it. This principle applies as directly to writing R code as it does to any other use of AI — a model can return code that runs without error and still be wrong, so nothing generated in this module should be trusted simply because it executed successfully.
This module introduces R's core data structures — vectors, factors, data frames, and lists — through applied exploration of three real datasets, rather than through a syntax lecture. Each dataset is used to motivate one or two specific structures, and each task is completed by prompting an AI model for R code rather than being handed a complete script.
R and RStudio must be installed before proceeding. If they are already installed, continue to Section 3.
Windows:
macOS:
.pkg file appropriate for your macOS version and follow the installation prompts.Go to the RStudio download page, select "RStudio Desktop," and download the installer appropriate for your operating system.
version and press Enter. Record the version of R installed on your machine.
pacman simplifies installing and loading R packages. In the console, run:
install.packages("pacman")
library(pacman)
p_load(readxl, ggplot2)
The working directory tells R where to look for files by default. Two methods are available.
In RStudio's menu bar, select Session > Set Working Directory > Choose Directory, then navigate to and select a folder named "Math and Coding Camp." Create this folder first if it does not yet exist, and place the datasets for this module inside it once they are provided.
The template below uses the word path as a stand-in — replace it (including removing the word itself, but keeping the quotation marks) with the actual location of the "Math and Coding Camp" folder on your machine.
C:\Users\Name\Documents\...), which R does not accept as-is — replace each single backslash with a forward slash, or double it (\\), before pasting it in place of path.path without modification.
setwd("path")
setwd("C:/Users/student/Documents/Math and Coding Camp")
setwd("path")
setwd("/Users/student/Desktop/Math and Coding Camp")
path was fully replaced with that location.
getwd() in the console to confirm it points to the correct folder.
R provides a direct way to determine what kind of object you are working with: the class() function. This function is used throughout the remainder of this module and should be treated as the primary tool for answering the question "what type of structure is this?"
a <- c(4, 8, 15, 16, 23)
b <- c("red", "green", "blue")
d <- TRUE
e <- list(count = 5, label = "sample")
class(a)
class(b)
class(d)
class(e)
class() line, state your prediction. Run the code and compare your predictions against the actual output. Note any discrepancies.
Each of the three datasets used in this module must be imported before it can be explored. Two methods are available: RStudio's point-and-click interface, or a short line of code.
In the Environment pane, select Import Dataset, then choose From Text (base) for .csv files or From Excel for .xlsx files. Select the file, confirm the preview, and click Import.
The two file formats used in this module require different functions: read.csv() for CSV files, and read_excel() — from the readxl package — for Excel files. Both return a data frame. Use class() from the previous section to confirm this once each file is imported.
life_exp <- read.csv("US_Life_expectancy.csv")
head(life_exp)
air <- read.csv("Air_Quality.csv")
head(air)
library(readxl)
ev <- read_excel("Electric_Vehicle_Population_Data.xlsx")
head(ev)
library(readxl) to be run first; the CSV imports do not require any additional package.
life_exp, air, and ev — appear in the Environment pane before continuing. Run class() on each to confirm all three are data frames.
The three datasets below are ordered by size and complexity. Each is used to introduce one or two data structures through a short sequence of exercises. Complete each segment, review its output, and confirm you understand the result before proceeding to the next.
This dataset introduces the data frame and the vector.
class(life_exp) and class(life_exp$Average_Life_Expectancy) separately. Using this output as evidence, state what a data frame is and what a vector is.
str(life_exp)
class(life_exp)
class(life_exp$Average_Life_Expectancy)
A data frame is a collection of vectors of equal length, aligned by row and stored as columns. A single column extracted on its own — life_exp$Average_Life_Expectancy — is a vector in its own right.
This dataset introduces the factor, using a mix of numeric and repeated categorical text columns drawn from a New York City public health dataset.
str(air)
unique(air$Name)
length(unique(air$Name))
class() on the column before and after conversion. State what changed and what did not.
class(air$Name)
air$Name <- factor(air$Name)
class(air$Name)
levels(air$Name)
A factor remains a vector; R additionally records that its values belong to a fixed set of categories. This distinction is what enables grouping, counting, and category-based visualization in later work.
This dataset introduces the list and demonstrates that the same operations used on small files apply without modification at substantially larger scale.
Make column and run your prompt. Record how many rows remain after filtering.
tesla <- subset(ev, Make == "TESLA")
nrow(tesla)
class() on the resulting summary object to determine its structure. Independently verify one value in the output — for example, by recomputing the average manually or inspecting several raw rows — and record what you checked.
tesla_summary <- list(
count = nrow(tesla),
avg_range = mean(tesla$Electric_Range, na.rm = TRUE)
)
tesla_summary
class(tesla_summary)
The object tesla_summary is a list — the one structure in this module that holds elements of different types together without requiring a consistent row-and-column shape. A data frame requires that shape; a list does not.
This module has covered R's four core data structures through applied work with three datasets: the data frame as a bundle of aligned vectors, the vector as a single column or sequence of values, the factor as a vector with a fixed set of categories, and the list as a flexible container for elements of differing type. class() was used throughout as the direct means of confirming which structure is in use, rather than relying on inference alone.
The underlying practice — supplying an AI model with a role, a task, context, and a format, and then independently verifying its output — applies equally to code and to prose, and should be carried forward into subsequent work in this camp.