Vectors

A vector is R's most fundamental data structure — even a single number like 5 is technically a vector of length 1. Most of what makes R feel different from other languages comes down to vectors and how operations apply to every element at once.

Creating a vector with c()

R vectors.R
scores <- c(88, 92, 79, 95)
scores
Console
[1] 88 92 79 95

c() ("combine") is how you build a vector out of individual values. The single [1] at the start of the line means this printed line begins at position 1 — for a vector long enough to wrap across several printed lines, each new line restarts with the index of its first value on that line, which is a genuinely useful way to keep track of where you are in a long vector.

Indexing starts at 1

R indexing.R
scores[1]
scores[4]
Console
[1] 88
[1] 95
Note: R vectors are indexed starting at 1, not 0 like most other languages. scores[0] doesn't error either — it silently returns numeric(0), a zero-length vector, rather than complaining about an out-of-range index. Coming from a 0-indexed language, that combination (off-by-one AND silent on the mistake) is worth watching for.

Vectorized operations

Arithmetic on a vector applies to every element without writing a loop:

R vectorized.R
scores + 5
Console
[1] 93 97 84 100

Recycling

When two vectors of different lengths are combined, R "recycles" — repeats — the shorter one to match the longer:

R recycling.R
c(1, 2, 3, 4) + c(10, 20)
Console
[1] 11 22 13 24

c(10, 20) gets recycled to c(10, 20, 10, 20) before the addition happens, so the result pairs up as 1+10, 2+20, 3+10, 4+20. Recycling works quietly when the shorter vector's length divides evenly into the longer one; when it doesn't, R still does the recycling but prints a warning that the lengths aren't a clean multiple.