01 / 20

Data Frames
in R

Master the fundamental data structure of R: create, inspect, and manipulate data frames to organize rows and columns of real-world data.

R Programming

What Is a Data Frame?

A data frame is R's primary structure for storing tabular data: information organized into rows and columns, much like a spreadsheet. Each column is a variable (a vector of a single type), and each row is an observation.

Anatomy of a Data Frame

name age passed 1 "Alice" 17 TRUE 2 "Bob" 16 FALSE 3 "Clara" 18 TRUE character numeric logical 3 rows (observations) × 3 columns (variables) ← column row →

Why Data Frames Matter

★ Standard Format
CSV files, databases, and APIs all produce tabular data. Data frames are how R represents it.
★ Mixed Types
Unlike matrices, data frames hold different types in each column: text, numbers, and booleans together.
★ Ecosystem Support
Nearly every R package (ggplot2, dplyr, tidyr) is built around data frames as the core input.

Creating a Data Frame with \( \texttt{data.frame()} \)

The \( \texttt{data.frame()} \) function takes named vectors as arguments. Each vector becomes a column, and the name you give it becomes the column header.

students <- data.frame( name = c("Alice", "Bob", "Clara"), age = c(17, 16, 18), passed = c(TRUE, FALSE, TRUE) )

The Core Rule of Data Frames

col 1 "Alice" "Bob" "Clara" length = 3 col 2 17 16 18 length = 3 col 3 TRUE FALSE TRUE length = 3 = = All columns must have equal length

Columns vs Rows

Columns Rows
Also called Variables / Fields Observations / Records
Data type Homogeneous (one type per column) Heterogeneous (mixed types across columns)
Access syntax \( \texttt{df\$col} \) or \( \texttt{df[, "col"]} \) \( \texttt{df[i, ]} \)
Counted by \( \texttt{ncol(df)} \) \( \texttt{nrow(df)} \)
Think of it as One vector A slice across all vectors

Inspecting with Key Functions

\( \texttt{str(df)} \)
Shows the structure: column names, types, and first values. Your go-to diagnostic.
\( \texttt{head(df)} \)
Returns the first 6 rows. Use \( \texttt{head(df, 3)} \) to see fewer.
\( \texttt{dim(df)} \)
Returns a vector of two numbers: rows and columns.
\( \texttt{names(df)} \)
Returns a character vector of all column names.
\( \texttt{summary(df)} \)
Shows min, max, mean, and quartiles for numeric columns; counts for factors.

How to Build and Check a Data Frame

1
Plan your columns. Decide what variables you need and what type each will be (character, numeric, logical).
2
Create equal-length vectors. Use \( \texttt{c()} \) to build each column vector with the same number of elements.
3
Combine with \( \texttt{data.frame()} \). Pass named vectors: \( \texttt{data.frame(name = ..., age = ...)} \).
4
Inspect immediately. Run \( \texttt{str()} \) to verify column types and \( \texttt{dim()} \) to confirm dimensions.
5
Access and subset. Use \( \texttt{df\$col} \) for columns, \( \texttt{df[i, ]} \) for rows, or \( \texttt{df[i, j]} \) for specific cells.

Example 1: Creating a Data Frame

# Build a data frame of 4 students roster <- data.frame( student = c("Ada", "Ben", "Cal", "Dee"), grade = c(92, 85, 78, 95), honors = c(TRUE, FALSE, FALSE, TRUE) )
> str(roster) 'data.frame': 4 obs. of 3 variables: $ student: chr "Ada" "Ben" "Cal" "Dee" $ grade : num 92 85 78 95 $ honors : logi TRUE FALSE FALSE TRUE

Example 2: Accessing Columns and Rows

# Access the "grade" column roster$grade # [1] 92 85 78 95 # Access row 2 (all columns) roster[2, ] # student grade honors # 2 Ben 85 FALSE # Access a single cell: row 3, column "grade" roster[3, "grade"] # [1] 78

Example 3: Filtering Rows

# Students with grade > 90 top_students <- roster[roster$grade > 90, ] top_students
student grade honors 1 Ada 92 TRUE 4 Dee 95 TRUE

The expression \( \texttt{roster\$grade > 90} \) produces a logical vector: \( \texttt{TRUE, FALSE, FALSE, TRUE} \). When used inside the brackets, R keeps only the rows where the condition is \( \texttt{TRUE} \).

Adding a New Column

# Add a "letter" column roster$letter <- ifelse( roster$grade >= 90, "A", ifelse(roster$grade >= 80, "B", "C") )
> roster student grade honors letter 1 Ada 92 TRUE A 2 Ben 85 FALSE B 3 Cal 78 FALSE C 4 Dee 95 TRUE A

Understanding Bracket Notation

\( \texttt{df[rows, columns]} \)
Rows (before comma)
\( \texttt{df[1:3, ]} \), \( \texttt{df[c(T,F), ]} \)
Cols (after comma)
\( \texttt{df[, "name"]} \), \( \texttt{df[, 1:2]} \)
Both specified
\( \texttt{df[2, "grade"]} \rightarrow \text{single cell} \)

Common Mistakes to Avoid

✕ Mismatched Lengths
Columns with different numbers of elements cause errors or silent recycling bugs.
✕ Forgetting the Comma
Writing \( \texttt{df[1]} \) selects a column, not a row. Use \( \texttt{df[1, ]} \) for row 1.
✕ Quoting Column Names
With \( \texttt{\$} \), don't quote: \( \texttt{df\$name} \). With brackets, do quote: \( \texttt{df[, "name"]} \). Mixing these up causes errors.

Summary: Essential Functions

Function Purpose Returns
\( \texttt{data.frame()} \) Create a data frame data.frame object
\( \texttt{str()} \) Show internal structure Types, dimensions, preview
\( \texttt{head() / tail()} \) Preview first/last rows Subset data frame
\( \texttt{dim() / nrow() / ncol()} \) Get dimensions Numeric vector or integer
\( \texttt{names()} \) Get or set column names Character vector
\( \texttt{summary()} \) Descriptive statistics Per-column summaries
\( \texttt{df\$col / df[i, j]} \) Access elements Vector, data.frame, or value

Question 1 of 5

Which function creates a new data frame from scratch in R?

Question 2 of 5

Given a data frame \( \texttt{df} \), what does \( \texttt{df[3, ]} \) return?

Question 3 of 5

What is the core constraint that distinguishes a data frame from a plain list in R?

Question 4 of 5

Which function would you use to quickly see the column names, types, and a preview of each column's values?

Question 5 of 5

How many rows does \( \texttt{result} \) contain, and what are the values in its \( \texttt{x} \) column?