Picking Elements with [ ]
Lesson 4 of 8 · 11 min
Square brackets select positions
To get at one element of a vector, write the vector's name followed by the position in square brackets. R counts from 1, so temps[1] is the first value. Inside the brackets you can put a single number, a vector of positions built with c(), or a range built with the colon. The order you give is the order you get back, so temps[c(3, 1)] returns the third value first.
temps <- c(21.5, 23.1, 19.8, 24.6, 22.0, 20.3, 25.2) temps[1] #> [1] 21.5 temps[3] #> [1] 19.8 temps[c(1, 3)] #> [1] 21.5 19.8 temps[2:4] #> [1] 23.1 19.8 24.6 temps[c(3, 1)] #> [1] 19.8 21.5
Negative positions drop elements
A negative index means everything except. temps[-1] is the vector without its first element, and a negative range drops a block. Note the parentheses in -(1:3): without them, -1:3 would be read as the sequence from -1 to 3, which mixes negative and positive positions and produces an error. You cannot combine positive and negative indices in one call.
temps[-1] #> [1] 23.1 19.8 24.6 22.0 20.3 25.2 temps[-(1:3)] #> [1] 24.6 22.0 20.3 25.2
The last element, and positions that do not exist
R has no special syntax for the last element. The idiom is to ask for position length(temps), which works for any length. Asking for a position beyond the end is not an error: R returns NA, the marker for a missing value. This is a frequent source of unexplained NA in later calculations, because a typo in an index produces no message at all. Position zero returns an empty vector, again without complaint.
temps[length(temps)] #> [1] 25.2 temps[10] #> [1] NA temps[0] #> numeric(0)
Changing elements in place
The same bracket notation on the left of <- writes into the vector instead of reading from it. You can replace one element or several at once; with several positions and a single value on the right, the value is recycled into each position. Unlike c(temps, 18.4) in the previous lesson, this does modify temps.
temps[2] <- 23.5 temps #> [1] 21.5 23.5 19.8 24.6 22.0 20.3 25.2 temps[c(1, 7)] <- 0 temps #> [1] 0.0 23.5 19.8 24.6 22.0 20.3 0.0
Reading and writing look alike, so be deliberate: the bracket on the right side of an arrow extracts, on the left side it overwrites. There is no undo; if you clobber a value, re-run the line that created the vector.
Why this matters for data
Indexing is how you answer specific questions about a dataset: the value on the third day, the first week of readings, all measurements except the faulty one. In the next lessons the thing inside the brackets becomes a condition rather than a number, and the same syntax will select every element that satisfies it. Positions are the foundation for that.
temps[0] is not the first element; it is an empty vector, and no error tells you so.x <- c(5, 10, 15, 20), what does x[-2] return?Sign in to answer and track your progress.
Sign in