Data Structures in R
R's true power comes from its rich set of built-in data structures. Understanding vectors, matrices, arrays, and factors is essential before moving on to data frames.
1. Vectors — The Building Block of R
A vector is an ordered collection of elements of the same data type. It's the most fundamental structure in R — even a single number is technically a vector of length 1.
numbers <- c(10, 20, 30, 40)
names <- c("Alice", "Bob", "Carol")
flags <- c(TRUE, FALSE, TRUE)
length(numbers) # 4
numbers[2] # 20 (1-indexed!)
numbers[c(1, 3)] # 10 30
numbers[numbers > 15] # 20 30 40 (logical subsetting)
2. Vector Operations Are Vectorized
Arithmetic on vectors is applied element-wise automatically — no loops needed:
a <- c(1, 2, 3)
b <- c(10, 20, 30)
a + b # 11 22 33
a * 2 # 2 4 6
sum(a) # 6
mean(b) # 20
3. Matrices — Two-Dimensional Data
A matrix is a 2D structure where all elements share the same type.
m <- matrix(1:6, nrow = 2, ncol = 3)
print(m)
# [,1] [,2] [,3]
# [1,] 1 3 5
# [2,] 2 4 6
m[1, 2] # 3 (row 1, col 2)
m[, 2] # entire column 2: 3 4
m[1, ] # entire row 1: 1 3 5
t(m) # transpose
dim(m) # 2 3
4. Arrays — Multi-Dimensional Extensions
An array generalizes a matrix to more than two dimensions:
arr <- array(1:24, dim = c(2, 3, 4))
dim(arr) # 2 3 4
arr[1, 2, 3] # single element at that position
5. Factors — Categorical Data
A factor stores categorical variables with fixed, known levels — ideal for things like survey responses, grades, or groups in statistical models.
grades <- factor(c("A", "B", "A", "C", "B"),
levels = c("A", "B", "C"))
levels(grades) # "A" "B" "C"
table(grades) # frequency count per level
# Ordered factor (has a meaningful order)
size <- factor(c("Small", "Large", "Medium"),
levels = c("Small", "Medium", "Large"),
ordered = TRUE)
size[1] < size[2] # TRUE (Small < Large)
6. Comparing the Four Structures
| Structure | Dimensions | Data Type Rule | Typical Use |
|---|---|---|---|
| Vector | 1D | Single type | A single column of values |
| Matrix | 2D | Single type | Numeric computations, linear algebra |
| Array | N-D | Single type | Multi-dimensional numeric data |
| Factor | 1D | Categorical labels | Grouping variables in models |
7. Production-Ready Checklist
- ✅ Master vector creation and indexing — the foundation of everything else in R.
- ✅ Understand vectorized operations — avoid unnecessary loops.
- ✅ Use matrices for 2D single-type data — and arrays for higher dimensions.
- ✅ Use factors for categorical variables — especially before statistical modeling.
Ready to master R Programming?
Build real-world data analysis and visualization projects with hands-on training, mentor-led sessions, and placement support.
.png)