01 / 20

Subsetting
Data Frames

Master the art of selecting rows and columns from data frames using R's powerful bracket notation and the dollar sign operator.

R Programming

What Is a Data Frame?

A data frame is R's primary structure for storing tabular data: a rectangular collection of values organized into rows (observations) and columns (variables). Think of it like a spreadsheet inside your code.

name age score 1 "Alice" 23 88 2 "Bob" 31 92 3 "Cara" 27 75 4 "Dan" 19 81 columns (variables) → rows →

Why Subset a Data Frame?

Real data sets contain far more information than you need for any single analysis. Subsetting lets you focus on exactly the data that matters.

Filter Rows
Keep only observations that meet a condition, like students who scored above 80.
Select Columns
Extract just the variables you need for a particular plot or calculation.
Isolate Values
Pull out a single cell, row, or column to inspect or transform it.

The Two Core Operators

R gives you two fundamental tools for subsetting data frames. Every technique you learn builds on these.

[ , ] Bracket Notation
The universal subsetting operator. Takes two arguments: rows (before the comma) and columns (after the comma). Omit either to select all.
$ Dollar Sign
A shortcut to extract a single column by name. Returns that column as a vector. Quick and readable.

Bracket Notation Explained

df [ rows , cols ] Which rows? numbers, logical, blank Which columns? numbers, names, blank the comma is required!
1
Leave rows blank to select all rows: \(\text{df}[ , 2]\)
2
Leave cols blank to select all columns: \(\text{df}[1, ]\)
3
Specify both to pinpoint exact cells: \(\text{df}[1, 2]\)

The $ Dollar Sign Operator

The $ operator extracts a single column from a data frame and returns it as a vector. It is the most common way to access one variable.

R
# Extract the "score" column as a vector
df$score
# [1] 88 92 75 81

# Use it in calculations
mean(df$score)
# [1] 84

# Use it for logical conditions
df$score > 80
# [1] TRUE TRUE FALSE TRUE

[ , ] vs $: Key Differences

\(\text{df}[ , ]\) \(\text{df}\$\text{col}\)
Selects Rows, columns, or both One column only
Returns Data frame or vector Always a vector
By number? ✓ Yes ✕ No
By name? ✓ Yes (quoted) ✓ Yes (unquoted)
Multiple cols? ✓ Yes ✕ No
Row filtering? ✓ Yes ✕ No

Four Ways to Subset with Brackets

By Position
Use integer indices: \(\text{df}[1, 3]\) gets row 1, column 3.
By Name
Use quoted strings: \(\text{df}[, \text{"age"}]\) gets the age column.
By Logic
Use TRUE/FALSE vectors: \(\text{df}[\text{df}\$\text{age} > 20, ]\) filters rows.
By Exclusion
Use negative indices: \(\text{df}[, -2]\) drops column 2.

How to Apply Subsetting

1
Identify what you need: Are you selecting columns, filtering rows, or both?
2
Choose your operator: Single column? Use $. Anything more complex? Use [ , ].
3
Write the row condition before the comma: a number, a vector, a logical expression, or leave blank for all rows.
4
Write the column selector after the comma: a number, a vector of names, or leave blank for all columns.
5
Test your result: Check dimensions with dim() or str() to verify you got what you expected.

Example 1: Selecting Columns

R
# Our data frame
df <- data.frame(
  name  = c("Alice", "Bob", "Cara", "Dan"),
  age   = c(23, 31, 27, 19),
  score = c(88, 92, 75, 81)
)

# Method 1: by name using $
df$name
# [1] "Alice" "Bob" "Cara" "Dan"

# Method 2: by position using brackets
df[, 2]
# [1] 23 31 27 19

# Method 3: multiple columns by name
df[, c("name", "score")]

Example 2: Filtering Rows

R
# Get row 1
df[1, ]
#    name age score
# 1 Alice  23    88

# Get rows 2 through 4
df[2:4, ]

# Logical filter: students older than 20
df[df$age > 20, ]
#    name age score
# 1 Alice  23    88
# 2   Bob  31    92
# 3  Cara  27    75

Example 3: Rows + Columns Together

R
# Names of students who scored above 80
df[df$score > 80, "name"]
# [1] "Alice" "Bob" "Dan"

# Names and scores of those students
df[df$score > 80, c("name", "score")]
#    name score
# 1 Alice    88
# 2   Bob    92
# 4   Dan    81

# A single cell: row 2, column "name"
df[2, "name"]
# [1] "Bob"
name age score 1 Alice 23 88 2 Bob 31 92 3 Cara 27 75 4 Dan 19 81 ✓ ✓ ✓

Negative Indexing: Dropping Data

In R, a negative index means "everything except this." Use it to exclude specific rows or columns without listing everything you want to keep.

R
# Drop column 2 (age)
df[, -2]
#    name score
# 1 Alice    88
# 2   Bob    92
# 3  Cara    75
# 4   Dan    81

# Drop rows 1 and 3
df[-c(1, 3), ]
#   name age score
# 2  Bob  31    92
# 4  Dan  19    81

Logical Subsetting Deep Dive

Logical subsetting is the most powerful technique. Build conditions using comparison operators, then pass the result to the row position.

R
# Combine conditions with & (AND)
df[df$age > 20 & df$score > 80, ]
#    name age score
# 1 Alice  23    88
# 2   Bob  31    92

# Use | (OR) for either condition
df[df$age < 21 | df$score > 90, ]
#   name age score
# 2  Bob  31    92
# 4  Dan  19    81
& AND
Both conditions must be TRUE
| OR
At least one must be TRUE
! NOT
Flips TRUE to FALSE

Common Mistakes to Avoid

✕ Forgetting the Comma
Writing \(\text{df}[1]\) instead of \(\text{df}[1, ]\) selects column 1, not row 1. The comma separates rows from columns.
✕ Unquoted Names in [ ]
Writing \(\text{df}[, \text{name}]\) instead of \(\text{df}[, \text{"name"}]\). Column names must be in quotes inside brackets (but not with $).
✕ Using = Instead of ==
Writing \(\text{df}[\text{df}\$\text{age} = 23, ]\) instead of \(\text{df}[\text{df}\$\text{age} == 23, ]\). Single = is assignment; double == is comparison.
✕ Mixing + and - Indices
Writing \(\text{df}[\text{c}(1, -3), ]\) throws an error. You must use all positive or all negative in one expression.

Summary Reference Table

Goal Syntax Returns
One column (vector) \(\text{df}\$\text{col}\) Vector
One column (data frame) \(\text{df}[, \text{"col"}, \text{drop}=\text{FALSE}]\) Data frame
Multiple columns \(\text{df}[, \text{c}(\text{"a"},\text{"b"})]\) Data frame
One row \(\text{df}[1, ]\) Data frame
Filter rows \(\text{df}[\text{df}\$x > 5, ]\) Data frame
Single cell \(\text{df}[2, \text{"col"}]\) Scalar
Exclude column \(\text{df}[, -2]\) Data frame

Question 1 of 5

Given a data frame df with columns name, age, and score, which expression returns the age column as a vector?

Question 2 of 5

What does \(\text{df}[3, ]\) return?

Question 3 of 5

Which expression correctly filters for all rows where \(\text{score} > 85\)?

Question 4 of 5

What does \(\text{df}[, -1]\) do?

Question 5 of 5

You need the names and scores of students whose \(\text{age} \geq 25\). Which expression accomplishes this?