R R

R: Vectors & Indexing

What you will learn

Vectors are R's fundamental data structure. Everything in R is built on vectors — even a single number is a vector of length 1.

Creating vectors with c()

fruits <- c("apple", "banana", "cherry")  # character vector
numbers <- c(1, 2, 3, 4, 5)                # numeric vector
sequence <- 1:5                            # shortcut: 1, 2, 3, 4, 5
repeated <- rep(10, 3)                     # 10, 10, 10

The c() function combines values into a vector. All elements must be the same type — if you mix types, R coerces them (usually to character).

1-based indexing

R uses 1-based indexing (the first element is index 1):

fruits[1]          # "apple"
fruits[c(1, 3)]    # "apple" "cherry" (multiple indices)
fruits[-2]         # "apple" "cherry" (exclude index 2)

Vectorized operations

R operates on entire vectors at once (no explicit loops needed):

x <- 1:5
y <- x * 2             # 2, 4, 6, 8, 10 (multiply each element)
z <- x + y             # 3, 6, 9, 12, 15 (element-wise)
sqrt(x)                # 1.00, 1.41, 1.73, 2.00, 2.24
sum(x)                 # 15
mean(x)                # 3

This vectorization is one of R's most powerful features — it avoids slow for loops.

Common mistakes

  • Using 0-based indexing (like Python) — fruits[0] returns an empty vector, not "apple".
  • Mixing types in c() — R silently coerces to the most flexible type (usually character).
  • Forgetting that 1:5 creates a vector of integers, but c(1, 2, 3, 4, 5) creates numeric (double) by default.
  • Using = to name vector elements outside of c() — use names() function.

Quick check below!