Vectors are the fundamental data structure in R. All elements must be the same type. Key creation functions: c(), seq(), rep(). Arithmetic is vectorised — no loops needed for element-wise operations.
# Create vectors
v <- c(3, 1, 4, 1, 5, 9, 2, 6)
s <- seq(1, 10, by = 2) # 1 3 5 7 9
r <- rep(c("a", "b"), times = 3) # a b a b a b
# Vectorised arithmetic
v * 2
v + s[1:length(v)]
# Summary statistics
length(v); sum(v); mean(v); sd(v); var(v)
range(v); min(v); max(v)
# Sorting and ordering
sort(v)
order(v) # indices that would sort v
rev(v)
# Logical tests
v > 3 # returns logical vector
which(v > 3) # indices where TRUE
any(v > 8); all(v > 0)
# ── Example using iris ──────────────────────────────────────────
sl <- iris$Sepal.Length # extract a column as vector
length(sl)
sum(sl); mean(sl); sd(sl); range(sl)
# Filter
sl[sl > 6]
sl[iris$Species == "setosa"]
# Sequence of indices
sl[1:10]
sl[seq(1, 150, by = 10)]