Indexing and subsetting

R · Essentials · 12 min

Subsetting is how you filter and reshape every kind of data in R.

R indexes from 1. The [ operator accepts four kinds of index:

  • Positive integers select those positions: x[c(1, 3)]. Out-of-range positions give NA.
  • Negative integers drop positions: x[-1] is everything but the first. You can't mix positive and negative.
  • Logical vectors keep elements where the index is TRUE: x[x > 10]. This is how you filter.
  • Character vectors select by name: x[c("a", "b")] for a named vector.

Name elements with c(a = 1, b = 2) or names(x) <- c("a", "b").

Subsetting works on the left of an assignment too: x[x < 0] <- 0 replaces every negative value in one step, no loop needed. Assigning beyond the end extends the vector, filling gaps with NA.

which(cond) turns a logical vector into the positions that are TRUE, and which.max(x) finds the position of the maximum. %in% tests membership: x[x %in% c(2, 4)].

x[0] is an empty vector, not the first element, which trips up people coming from zero-based languages. Missing values in a logical index produce NA elements, so filter with x[!is.na(x) & x > 10] or x[which(x > 10)] when data may contain NA.

Example

x <- c(a = 5, b = -2, c = 9, d = -7)
print(x[c(1, 3)])          #> a c
                           #> 5 9
print(x[-1])               #> b  c  d / -2  9 -7
print(x[x > 0])            #> a c / 5 9
print(x[c("d", "a")])      #> d  a / -7  5
print(which(x < 0))        #> b d / 2 4

x[x < 0] <- 0              # replace negatives in place
print(unname(x))           #> [1] 5 0 9 0

y <- c(3, NA, 12)
print(y[y > 5])            #> [1] NA 12
print(y[which(y > 5)])     #> [1] 12
print(length(x[0]))        #> [1] 0

Remember

  • Indexes start at 1; negative indexes drop elements
  • A logical index filters: x[x > 0]
  • Assign into a subset to modify many elements at once
  • Use which() or !is.na() when NAs may be present

Watch out for

  • Using x[0] for the first element, which returns an empty vector.

Check yourself

  1. x <- c(10, 20, 30). What is x[-2]?
  2. y <- c(3, NA, 12). What does y[y > 5] return?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: cran.r-project.org/doc/manuals/r-release/R-intro.html#Index-vectors