Skip to content
AgileLogics
7 min read

Vectors

Prerequisites: Numbers and arithmetic

The vector is R's most fundamental data structure: an ordered collection of values of the same type. In fact, a single number in R is just a vector of length one — which is why output starts with [1].

Real-world analogy: a vector is a single column in a spreadsheet — a row of cells, all holding the same kind of data.

Creating vectors

c() ("combine") creates a vector:

scores <- c(72, 95, 88, 64)
names <- c("Ada", "Linus", "Grace", "Alan")
passed <- c(TRUE, TRUE, TRUE, FALSE)

scores
length(scores)
1:5
seq(0, 1, by = 0.25)
rep("x", 3)
[1] 72 95 88 64
[1] 4
[1] 1 2 3 4 5
[1] 0.00 0.25 0.50 0.75 1.00
[1] "x" "x" "x"

Indexing starts at 1

Unlike most programming languages, R counts from 1:

scores <- c(72, 95, 88, 64)
scores[1]
scores[c(1, 3)]
scores[-1]
scores[scores > 80]
[1] 72
[1] 72 88
[1] 95 88 64
[1] 95 88
  • scores[-1] means "everything except element 1".
  • scores[scores > 80] keeps elements where the condition is TRUE — logical indexing, one of R's most useful features.

Vectorized operations

Arithmetic and many functions work on every element at once:

prices <- c(10, 20, 30)
prices * 1.2
prices + c(1, 2, 3)
sqrt(c(4, 9, 16))
prices > 15
[1] 12 24 36
[1] 11 22 33
[1] 2 3 4
[1] FALSE  TRUE  TRUE

No loop needed. Vectorized code is shorter, clearer, and much faster in R than writing loops yourself.

The [1] prefix, explained

When a vector is too long for one line, each new line starts with the position of its first element:

seq(10, 300, by = 10)
 [1]  10  20  30  40  50  60  70  80  90 100 110 120 130 140 150 160 170 180 190
[20] 200 210 220 230 240 250 260 270 280 290 300

The second line starts with element 20.

One type per vector

Mixing types converts everything to the most flexible type:

c(1, "two", TRUE)
[1] "1"    "two"  "TRUE"

Everything became text. (For mixed types, use a list — a later lesson.)

Common mistakes

  • Using index 0: scores[0] returns an empty vector, not the first element.
  • Reading past the end: scores[10] returns NA, not an error.

Practice

Create a vector of five temperatures in Celsius, convert them all to Fahrenheit (c * 9 / 5 + 32), and print only the ones above 70°F.

Show solution
celsius <- c(12, 18, 25, 31, 20)
fahrenheit <- celsius * 9 / 5 + 32
fahrenheit[fahrenheit > 70]
[1] 77.0 87.8