Vector (R)

A vector is R's most basic data structure: an ordered sequence of elements that all share the same type (numeric, character, logical, etc.). Even a single value in R is a length-1 vector.

R

Vectors are the heart of R. You build one with c() (combine), and every element must be the same atomic type — if you mix types, R silently coerces them all to the most general one (logical to numeric to character). There are no scalars in R: 5 is really a numeric vector of length 1.

Operations in R are vectorized: applying a function or arithmetic to a vector works element by element with no explicit loop, which is both concise and fast. Index a vector with [ ] using positions, logical masks, or names, and note that R indexing starts at 1, not 0.

Vectors underpin nearly everything else — a data frame column is a vector, a factor is a vector with levels, and a matrix is a vector with dimensions. Mastering vectors and vectorized thinking is the key to writing idiomatic R.

Syntax

v <- c(1, 2, 3, 4)
v[2]   # second element (1-indexed)

Examples

R

v <- c(10, 20, 30)
print(v * 2)
print(v[c(1, 3)])
print(sum(v))

Output:

[1] 20 40 60
[1] 10 30
[1] 60

Learn it in a lesson

See also

Back to the Dictionary