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.
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
Why Data Frames Matter
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.
The Core Rule of Data Frames
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
How to Build and Check a Data Frame
Example 1: Creating a Data Frame
Example 2: Accessing Columns and Rows
Example 3: Filtering Rows
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
Understanding Bracket Notation
Common Mistakes to Avoid
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
Consider the following R code:
\( \texttt{df <- data.frame(x = c(10, 20, 30), y = c("a", "b", "c"))} \)
\( \texttt{result <- df[df\$x > 15, ]} \)
How many rows does \( \texttt{result} \) contain, and what are the values in its \( \texttt{x} \) column?