Vectors — Indexing and Recycling
A vector is an ordered set of values of one type, indexed from 1, where negative indices drop positions, logical indices filter, and a shorter vector is recycled to match a longer one.
Trace indexing and recycling, including mismatched lengths and missing elements.
You have used kg since the first lesson. Now it is time to take the vector seriously, because nearly every other structure in R is built from vectors, and two of their rules, 1-based indexing and recycling, explain a huge share of R's surprises.
The rule
Index from 1; negatives drop; logicals filter; shorter vectors recycle.
A vector is an ordered set of values of one type. You make one with c(), a sequence such as 1:5 or seq(0, 20, by = 5), or rep("bean", 3). length() tells you how many elements it has.
Square brackets pick elements, and what you put inside decides how:
kg <- c(12.5, 8, 15, 3.5, 6) # plots A to E
kg[2] # 8 positive: keep position 2
kg[c(1, 3)] # 12.5 15 several positions
kg[-1] # 8 15 3.5 6 negative: drop position 1
kg[kg > 7] # 12.5 8 15 logical: keep where TRUE
kg[6] # NA past the end: NA, not an errorYou can mix several positive positions, or several negative ones, but not both: kg[c(-1, 2)] is an error (only 0's may be mixed with negative subscripts).
Names give elements labels you can index by:
names(kg) <- c("A", "B", "C", "D", "E")
kg["D"] # D 3.5Recycling is what happens when two vectors of different lengths meet in an operation. R repeats the shorter one until it matches the longer:
kg / 1000 # the single 1000 is reused 5 times
c(1, 2, 3, 4) + c(10, 20) # 11 22 13 24
kg * c(1, 1000) # works, but warns: 5 is not a multiple of 2When the longer length is a multiple of the shorter, recycling is silent. When it is not, R still recycles but warns that the longer object length is not a multiple of the shorter object length. Treat that warning as a bug report.