R, RStudio & Data Structures

An introduction to R's core data structures through applied exploration of real datasets, using AI-assisted prompting

Author
JP Adjadeh
Published
July 30, 2026

1. Introduction


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.

2. Setup


R and RStudio must be installed before proceeding. If they are already installed, continue to Section 3.

Installing R

Windows:

  1. Go to the R Project website.
  2. Select "Download R for Windows," then "base."
  3. Download and run the installer for the latest version of R.

macOS:

  1. Go to the R Project website.
  2. Select "Download R for macOS."
  3. Download the .pkg file appropriate for your macOS version and follow the installation prompts.

Installing RStudio

Go to the RStudio download page, select "RStudio Desktop," and download the installer appropriate for your operating system.

⚠ Quick Check
Open RStudio. In the console pane, type version and press Enter. Record the version of R installed on your machine.

Installing a Package Manager

pacman simplifies installing and loading R packages. In the console, run:

Code
install.packages("pacman")
library(pacman)
p_load(readxl, ggplot2)

Setting the Working Directory

The working directory tells R where to look for files by default. Two methods are available.

Method 1: Point-and-click (Windows and macOS)

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.

Method 2: By code

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.

ⓘ Note — Copying a Path
Windows: In File Explorer, right-click the folder and select "Copy as path." This produces a path using backslashes (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.

macOS: In Finder, hold Option and right-click the folder, then select "Copy '...' as Pathname." This produces a path using forward slashes, which can be pasted directly in place of path without modification.

Windows

Template
setwd("path")
Worked example
setwd("C:/Users/student/Documents/Math and Coding Camp")

macOS

Template
setwd("path")
Worked example
setwd("/Users/student/Desktop/Math and Coding Camp")
ⓘ Note
If R reports that it cannot change the working directory, the path itself needs to be corrected — this is not a sign that the function was used incorrectly. Confirm the exact location of your "Math and Coding Camp" folder — using Method 1 above if you are unsure — and check that path was fully replaced with that location.
⚠ Quick Check
Set your working directory using either method above, then run getwd() in the console to confirm it points to the correct folder.

3. Foundational Check: Determining Structure


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?"

Code
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)
⚠ Exercise 1
Before running each class() line, state your prediction. Run the code and compare your predictions against the actual output. Note any discrepancies.

4. Importing the Data


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.

Method 1: Point-and-click

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.

Method 2: By code

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.

Code
life_exp <- read.csv("US_Life_expectancy.csv")
head(life_exp)
Code
air <- read.csv("Air_Quality.csv")
head(air)
Code
library(readxl)
ev <- read_excel("Electric_Vehicle_Population_Data.xlsx")
head(ev)
ⓘ Note
The Excel import requires library(readxl) to be run first; the CSV imports do not require any additional package.
⚠ Quick Check
Confirm all three objects — life_exp, air, and ev — appear in the Environment pane before continuing. Run class() on each to confirm all three are data frames.

5. R's Core Data Structures


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.

Dataset 1 — Life Expectancy

DATASET 1 OF 3
File: US_Life_expectancy.csv
Size: 239 rows, 4 columns
Columns: Year, Gender, Average_Life_Expectancy, Age_adjusted_Death_Rate

This dataset introduces the data frame and the vector.

Segment 1: Structure and vectors

Mission Card — complete the prompt, then run it
You are a [role]. Using the life_exp object I already imported, write R code to [show me the structure of the data and the data type of the Average_Life_Expectancy column specifically].
⚠ Exercise 2
Run 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.
Guide code
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.

Dataset 2 — Air Quality

DATASET 2 OF 3
File: Air_Quality.csv
Size: approximately 14,000 rows, 9 columns
Columns: Unique_ID, Indicator_ID, Name, Measure, Measure_Info, Type_Name, Year, Place_Name, Data Value

This dataset introduces the factor, using a mix of numeric and repeated categorical text columns drawn from a New York City public health dataset.

Segment 1: Inspect column types

Mission Card — complete the prompt, then run it
You are a [role]. Using the air object I already imported, write R code to report [which columns are numeric and which are text].
⚠ Exercise 3
Run your prompt. Identify one text column whose values repeat frequently across rows.
Guide code
str(air)

Segment 2: Count unique values

Mission Card — complete the prompt, then run it
You are a [role]. For the column I identified in the air data frame, write R code to [list its unique values and count how many there are].
⚠ Exercise 4
Run your prompt. Record the number of unique values in the column you selected.
Guide code
unique(air$Name)
length(unique(air$Name))

Segment 3: Convert to a factor

Mission Card — complete the prompt, then run it
You are a [role]. Write R code to convert this column to a factor and [show me its class before and after the conversion].
⚠ Exercise 5
Run class() on the column before and after conversion. State what changed and what did not.
Guide code
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.

Dataset 3 — Electric Vehicle Population

DATASET 3 OF 3
File: Electric_Vehicle_Population_Data.xlsx
Size: approximately 194,000 rows, 17 columns
Format: Excel — the first non-CSV file in this module

This dataset introduces the list and demonstrates that the same operations used on small files apply without modification at substantially larger scale.

Segment 1: Subset to one manufacturer

Mission Card — complete the prompt, then run it
You are a [role]. Using the ev data frame I already imported, write R code to [filter the data to a single manufacturer of my choosing].
⚠ Exercise 6
Choose a manufacturer present in the Make column and run your prompt. Record how many rows remain after filtering.
Guide code
tesla <- subset(ev, Make == "TESLA")
nrow(tesla)

Segment 2: Build and verify a summary

Mission Card — complete the prompt, then run it
You are a [role]. Using this filtered data, write R code to build a named summary containing [the number of vehicles and their average electric range]. Also flag anything in the output that looks like missing or unusual data.
⚠ Exercise 7
Run your prompt, then run 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.
Guide code
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.

Conclusion


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.