R subsetting and indexing
last modified November 19, 2026
Subsetting is the act of taking part of an object: some elements of a vector,
some rows or columns of a table, or one component of a list. R expresses all
of these operations with the bracket, but the bracket behaves differently
depending on the object and on whether one or two brackets are used. This
article brings the rules together, compares positive, negative, logical, and
named indices, shows how which turns a condition into positions,
and explains why drop = FALSE matters when a result must stay a
table.
Positions and signs
A positive index selects the positions it names, in the order given. A negative index excludes the positions it names. A logical index selects the positions where it is true, and it is recycled when it is shorter than the vector. A comparison supplies such a logical vector directly.
scores <- c(72, 85, 90, 66, 78) print(scores[c(1, 5)]) print(scores[-c(1, 5)]) print(scores[c(TRUE, FALSE, TRUE, FALSE, TRUE)]) print(scores[scores >= 80])
The first selection keeps the first and the fifth score, and the second removes them. The logical vector selects the first, third, and fifth positions. The last line is the common filter: it keeps the values that satisfy a condition without naming any position at all.
$ Rscript vectors.R [1] 72 78 [1] 85 90 66 [1] 72 90 78 [1] 85 90
Positions from conditions
which converts a logical vector into the positions of its true
values, which is useful when the positions themselves are needed rather than
the selected values. which.max and which.min return
the position of the first extreme value.
scores <- c(Ada = 72, Grace = 85, Alan = 90, Edsger = 66) print(which(scores >= 80)) print(which.max(scores)) print(scores[which.max(scores)]) print(names(scores)[which.max(scores)])
Grace and Alan are at positions two and three. The maximum score is at position three, and indexing the vector with that position returns 90. The last line indexes the names with the same position, which yields the winner's name. A named vector keeps its names through most selections, which makes this pattern short.
$ Rscript which-positions.R
Grace Alan
2 3
Alan
3
Alan
90
[1] "Alan"
Names, recycling, and missing positions
A character index selects elements by name. A logical index shorter than the
vector is repeated from the beginning, and an index beyond the end of the
vector returns NA rather than an error. The last behaviour is
deliberate: it lets code extend a vector by assigning to a new position.
scores <- c(Ada = 72, Grace = 85, Alan = 90)
print(scores[c("Grace", "Ada")])
print(scores[c(TRUE, FALSE)])
print(scores[10])
The first selection returns the named values in the requested order. The two-element logical vector is recycled to select positions one and three. The tenth position does not exist, so R returns a missing value with a missing name. Mixing positive and negative indices in one call is an error, because the two intentions contradict each other.
$ Rscript name-subsetting.R Grace Ada 85 72 Ada Alan 72 90 <NA> NA
Matrices
A matrix takes two indices inside one pair of brackets: the row first, then
the column. A blank index means every row or every column. When a selection
leaves one row or one column, R drops the dimension and returns a vector
unless drop = FALSE is given.
m <- matrix(1:9, nrow = 3, byrow = TRUE,
dimnames = list(c("r1", "r2", "r3"), c("c1", "c2", "c3")))
print(m[2, ])
print(m[, c("c1", "c3")])
print(m[m > 5])
print(m[2, , drop = FALSE])
The second row is the vector 4, 5, 6, and the first and third columns form a
three-by-two matrix. The logical matrix m > 5 selects the
elements in column-major order and returns a plain vector. The last call keeps
the single row as a one-by-three matrix, which is the form required by
functions that expect two dimensions.
$ Rscript matrices.R c1 c2 c3 4 5 6 c1 c3 r1 1 3 r2 4 6 r3 7 9 [1] 7 8 6 9 c1 c2 c3 r2 4 5 6
Lists
On a list, the single bracket returns a list and the double bracket returns the element inside it. The dollar sign is shorthand for the double bracket with a name. A vector of names inside single brackets returns a smaller list, which is how several components are kept together.
student <- list(name = "Ada", scores = c(90, 85), passed = TRUE)
print(student["name"])
print(student[["name"]])
print(student$scores[2])
print(student[c("name", "passed")])
student["name"] still prints the $name heading,
while student[["name"]] prints the bare string. The second score
is reached by chaining the component selection with a position. The last call
keeps two components and returns a list of two elements.
$ Rscript lists.R $name [1] "Ada" [1] "Ada" [1] 85 $name [1] "Ada" $passed [1] TRUE
Data frames
A data frame takes two indices like a matrix, but the columns can have
different types. Selecting a single column with a blank row index returns a
vector; adding drop = FALSE preserves the one-column data frame.
Selecting several columns always returns a data frame.
students <- data.frame(
name = c("Ada", "Grace", "Alan"),
score = c(90, 85, 66),
subject = c("math", "art", "math")
)
print(students[students$score >= 80, c("name", "score")])
print(students[, "score"])
print(students[, "score", drop = FALSE])
The first selection keeps the two students with at least 80 points and only the name and score columns. The second returns the score column as a vector, and the third returns it as a data frame with one column. Row names carry over from the original table, so the one-column result still numbers its rows from one to three.
$ Rscript dataframes.R name score 1 Ada 90 2 Grace 85 [1] 90 85 66 score 1 90 2 85 3 66
Assignment through a subset
The bracket works on the left of an assignment as well as on the right. Assigning to selected positions replaces only those values and leaves the rest of the object unchanged. Assigning beyond the end grows the vector and fills the gap with missing values.
scores <- c(72, 85, 90, 66)
scores[scores < 70] <- 70
print(scores)
scores[5] <- 88
print(scores)
students <- data.frame(name = c("Ada", "Grace"), score = c(90, 25))
students$score[students$score < 50] <- NA
print(students)
The failing scores are raised to 70, and the new fifth position receives 88.
The data frame column is changed through a nested selection: first the
score column is selected, then the positions below 50 inside it
are replaced with NA. Assignment through a subset is the base R
way to recode values without rebuilding the object.
$ Rscript assignment.R [1] 72 85 90 70 [1] 72 85 90 70 88 name score 1 Ada 90 2 Grace NA
The subset function
subset is a convenience wrapper that evaluates its condition
inside the data frame, so column names can be written without the
students$ prefix. The select argument chooses
columns by name. The function is meant for interactive use; inside another
function, the bracket form is safer because it evaluates its arguments
normally.
students <- data.frame(
name = c("Ada", "Grace", "Alan"),
score = c(90, 85, 66),
subject = c("math", "art", "math")
)
print(subset(students, score >= 80, select = c(name, score)))
print(subset(students, subject == "math"))
The first call keeps the two passing students and only two columns. The second keeps the mathematics records, including the failing score. The row names show that the selected rows kept their original numbers, which is useful for tracing a result back to its source.
$ Rscript subset-function.R name score 1 Ada 90 2 Grace 85 name score subject 1 Ada 90 math 3 Alan 66 math
A complete example
The next script adds a percentage column to a table. It computes the lowest
and highest scores once, rescales every score with vectorised arithmetic, and
then selects the best record with which.max. The row names are
left in place so that the winner can be identified.
students <- data.frame(
name = c("Ada", "Grace", "Alan", "Edsger"),
score = c(90, 85, 66, 78)
)
lowest <- min(students$score)
highest <- max(students$score)
students$percent <- round((students$score - lowest) / (highest - lowest) * 100)
best <- students[which.max(students$score), ]
print(students)
print(best)
Ada has the highest score and therefore the percentage 100, Alan has the
lowest and therefore 0, and the other two fall in between. The expression
students[which.max(students$score), ] returns a one-row data
frame because the column index is blank. Replacing the blank with a column
name would return that single value instead.
$ Rscript report.R
name score percent
1 Ada 90 100
2 Grace 85 79
3 Alan 66 0
4 Edsger 78 50
name score percent
1 Ada 90 100
Next steps
The missing values article shows how
NA behaves inside these selections, and the
apply family article applies functions to
the rows, columns, and groups that this article selects. The dplyr article
later in the series rewrites the same filters with verbs such as
filter and select.
Source
The R Language Definition: indexing
R documentation: extract or replace parts of an object
In this article we have selected vector elements by position, by exclusion,
by name, and by condition. We turned conditions into positions with
which and which.max, and saw how logical indices
recycle and how out-of-range positions return NA. We indexed
matrices, lists, and data frames, used drop = FALSE to preserve
dimensions, assigned through a subset, and filtered a table with
subset. The series continues with
R missing values.
Author
List all R Language tutorials.