Skip to main content
R Programming
CHAPTER 09 Beginner

Matrices and Arrays

Updated: May 18, 2026
5 min read

# CHAPTER 9

Matrices and Arrays in R

1. Chapter Introduction

Matrices extend vectors to two dimensions — essential for linear algebra, statistical modeling, and tabular numeric computation. Arrays extend to n-dimensions. This chapter masters matrix creation, operations, and practical data analysis with matrices.

2. Creating Matrices

r
123456789101112131415161718192021222324252627282930313233
# matrix(data, nrow, ncol, byrow=FALSE)
# Default fills column-by-column (byrow=FALSE)
m1 <- matrix(1:12, nrow=3, ncol=4)
print(m1)
#      [,1] [,2] [,3] [,4]
# [1,]    1    4    7   10
# [2,]    2    5    8   11
# [3,]    3    6    9   12

# Fill by row
m2 <- matrix(1:12, nrow=3, ncol=4, byrow=TRUE)
print(m2)
#      [,1] [,2] [,3] [,4]
# [1,]    1    2    3    4
# [2,]    5    6    7    8
# [3,]    9   10   11   12

# Named rows and columns
sales <- matrix(
  c(12000, 15000, 18000,
    9000,  11000, 14000,
    7000,  8500,  11000),
  nrow=3, byrow=TRUE,
  dimnames=list(
    c("Laptop", "Phone", "Tablet"),
    c("Q1", "Q2", "Q3")
  )
)
print(sales)

dim(sales)     # 3 3 (rows, cols)
nrow(sales)    # 3
ncol(sales)    # 3

3. Matrix Indexing and Operations

r
123456789101112131415161718192021222324252627282930313233343536373839
# Indexing: [row, col]
sales["Laptop", "Q2"]   # 15000
sales[1, 2]              # 15000
sales[1, ]               # All of row 1 (Laptop across quarters)
sales[, "Q3"]            # All of column Q3 (all products Q3)
sales[1:2, 2:3]          # Sub-matrix

# Matrix arithmetic (element-wise)
m <- matrix(1:4, 2, 2)
m + 10        # Add 10 to all elements
m * 2         # Multiply all by 2
m ^ 2         # Square all elements

# Matrix operations
A <- matrix(c(1,2,3,4), 2, 2)
B <- matrix(c(5,6,7,8), 2, 2)
A + B         # Element-wise addition
A * B         # Element-wise multiplication (NOT matrix mult!)
A %*% B       # TRUE matrix multiplication!

t(A)          # Transpose
det(A)        # Determinant: -2
solve(A)      # Inverse matrix
solve(A, b=c(5,6))  # Solve Ax = b

# Row/Column operations
rowSums(sales)     # Total per product
colSums(sales)     # Total per quarter
rowMeans(sales)    # Average per product
colMeans(sales)    # Average per quarter
apply(sales, 1, max)  # Max per row
apply(sales, 2, min)  # Min per column

# rbind and cbind
q4 <- c(20000, 16000, 13000)
sales_4q <- cbind(sales, Q4=q4)   # Add column
# Add row
tablet2 <- matrix(c(5000,6000,7000,9000), nrow=1,
                   dimnames=list("Watch", c("Q1","Q2","Q3","Q4")))

4. Arrays (n-Dimensional)

r
12345678910111213141516171819
# 3D array: [rows, cols, layers]
sales_3d <- array(
  data = round(runif(24, 5000, 20000)),
  dim  = c(4, 3, 2),   # 4 products × 3 quarters × 2 years
  dimnames = list(
    c("Laptop", "Phone", "Tablet", "Watch"),
    c("Q1", "Q2", "Q3"),
    c("2023", "2024")
  )
)

# Access elements
sales_3d["Laptop", "Q2", "2024"]  # Single element
sales_3d[,,  "2024"]              # All 2024 data (4×3 matrix)
sales_3d["Laptop", , ]            # Laptop across all quarters/years

# Aggregate across dimensions
apply(sales_3d, 3, sum)  # Total by year
apply(sales_3d, 1, mean) # Average by product across all quarters/years

5. Common Mistakes

  • A * B vs A %*% B for matrix multiplication: * is element-wise. %*% is true matrix multiplication. This is a very common R error in linear algebra.
  • matrix(1:6, 2) fills by COLUMN: Default byrow=FALSE. Beginners often expect row-filling. Use byrow=TRUE if you're constructing row-wise.

6. MCQs

Question 1

matrix(1:6, 2) fills by?

Question 2

True matrix multiplication in R uses?

Question 3

t(A) does?

Question 4

apply(m, 1, sum) computes?

Question 5

cbind() combines matrices?

Question 6

dim(m) returns?

Question 7

solve(A) computes?

Question 8

Array vs matrix: arrays have?

Question 9

colMeans(m) computes?

Question 10

Element [2,3] in matrix m[2,3] means?

7. Interview Questions

  • Q: What is the difference between * and %*% for matrices in R?
  • Q: How do you solve a system of linear equations in R?

8. Summary

Matrices: 2D homogeneous arrays. Create with matrix(data, nrow, ncol, byrow). Index with [row, col]. Element-wise: +, *, ^. Matrix algebra: %*% (multiply), t() (transpose), det() (determinant), solve() (inverse/equations). Row/col aggregation: rowSums(), colMeans(), apply(m, margin, FUN). Arrays extend to n-dimensions.

9. Next Chapter Recommendation

In Chapter 10: Lists and Data Frames, we master R's most important data structures for heterogeneous data — perfect for real-world datasets.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·