The vector is R's fundamental data structure—atomic vectors hold elements of one type. Most functions are vectorized: operations apply element-wise without explicit loops.
Creating vectors
nums <- c(10, 20, 30)
chars <- c("a", "b", "c")
seq_vec <- seq(1, 5, by = 1)
rep_vec <- rep(1, times = 3)
Vectorized math and recycling
x <- c(1, 2, 3)
print(x * 2)
print(x + c(10, 20, 30))
Shorter vectors recycle in binary ops—watch for silent length mismatches (R warns when lengths are not multiples).
Indexing (1-based)
vals <- c(10, 20, 30, 40)
print(vals[1])
print(vals[c(1, 3)])
R indexes from 1, unlike Python's 0—off-by-one bugs are a common interview topic.
Important interview questions and answers
- Q: What does c() do?
A: Combines values into a vector—the c stands for combine/concatenate. - Q: Vectorization benefit?
A: Write x * 2 instead of looping—faster and clearer for numeric work.
Self-check
- What index is the first element in R?
- What function creates a sequence from 1 to 5?
Tip: R indexes from 1—off-by-one vs Python is a frequent bug in interviews.
Interview prep
- Why vectorization?
Element-wise ops are faster and clearer than manual loops for numeric work.
- 1-based indexing?
First element is
x[1], unlike zero-based languages like Python.