Vectors

The vector is R's fundamental data structure — even a single number is a vector of length 1.

6.1 Creating vectors

c(1, 2, 3)                      # combine
1:10                            # integer sequence
seq(0, 1, by = 0.25)            # 0.00 0.25 0.50 0.75 1.00
seq(1, 10, length.out = 4)      # 1 4 7 10
seq_len(5); seq_along(c("a", "b", "c"))   # safe sequences (handle length 0)
rep(c("a", "b"), times = 3)     # a b a b a b
rep(c("a", "b"), each = 2)      # a a b b
vector("numeric", 3)            # 0 0 0
numeric(3); character(2); logical(2)
rev(1:5)

6.2 Named vectors

ages <- c(alice = 30, bob = 25, carol = 35)
names(ages)
ages["bob"]
names(ages) <- toupper(names(ages))
unname(ages)

6.3 Indexing (subsetting) — six ways

x <- c(10, 20, 30, 40, 50)
x[1]                 # 10 — 1-based!
x[c(1, 3)]           # 10 30
x[-1]                # drop first: 20 30 40 50
x[-(1:2)]
x[x > 25]            # logical: 30 40 50
x[c(TRUE, FALSE)]    # recycled logical: 10 30 50
ages["alice"]        # by name
x[10]                # NA (out of bounds)
x[0]                 # numeric(0)
x[]                  # everything

6.4 Modifying

x[2] <- 99
x[x > 40] <- 0
x <- c(x, 60)          # append (copies the vector)
x <- append(x, 5, after = 0)
length(x) <- 3         # truncate

6.5 Vectorization & recycling

Prefer vectorized operations to loops — they're shorter and much faster.

c(1, 2, 3) * 2              # 2 4 6
c(1, 2, 3) + c(10, 20, 30)  # 11 22 33
1:6 + c(100, 200)           # 101 202 103 204 105 206 — shorter vector recycled
1:5 + 1:2                   # works, but warns: longer length not a multiple
sqrt(c(4, 9, 16))           # 2 3 4

6.6 Useful vector functions

x <- c(5, 3, 8, 1, 9, 2, 8)
length(x); sum(x); mean(x); median(x); var(x); sd(x); range(x); prod(x)
sort(x); sort(x, decreasing = TRUE); order(x); rank(x); rev(x)
unique(x); duplicated(x); table(x); tabulate(x)
which(x > 4)            # indices: 1 3 5 7
which.max(x); which.min(x)
head(x, 3); tail(x, 2)
cumsum(x); diff(x)
any(x > 8); all(x > 0)
ifelse(x > 4, "big", "small")
union(1:3, 2:5); intersect(1:3, 2:5); setdiff(1:5, 2:3); is.element(3, 1:5)
match(c("b", "z"), c("a", "b", "c"))   # 2 NA
paste0("id_", 1:3)                     # "id_1" "id_2" "id_3"