R Matrices

A matrix is a two-dimensional data structure with rows and columns. Every element in a matrix must be the same data type. Think of it as a spreadsheet with only numbers — organized in a grid of rows and columns.

Creating a Matrix

# matrix(data, nrow, ncol, byrow)
m <- matrix(1:9, nrow = 3, ncol = 3)
print(m)
     [,1] [,2] [,3]
[1,]   1    4    7
[2,]   2    5    8
[3,]   3    6    9

By default R fills a matrix column by column (top to bottom, left to right). Use byrow = TRUE to fill row by row instead.

m2 <- matrix(1:9, nrow = 3, ncol = 3, byrow = TRUE)
print(m2)
     [,1] [,2] [,3]
[1,]   1    2    3
[2,]   4    5    6
[3,]   7    8    9

Matrix Anatomy

         Column 1  Column 2  Column 3
Row 1  [   1         2         3   ]
Row 2  [   4         5         6   ]
Row 3  [   7         8         9   ]

Position [row, col]:
  m2[1, 1] = 1
  m2[2, 3] = 6
  m2[3, 2] = 8

Accessing Elements

m2[1, 2]      # Row 1, Col 2 → 2
m2[2, ]       # Entire Row 2 → 4 5 6
m2[, 3]       # Entire Col 3 → 3 6 9
m2[1:2, 2:3]  # Sub-matrix (rows 1-2, cols 2-3)

Matrix Properties

nrow(m2)        # 3 (number of rows)
ncol(m2)        # 3 (number of columns)
dim(m2)         # 3 3
length(m2)      # 9 (total elements)

Naming Rows and Columns

sales <- matrix(c(100, 200, 150, 300, 250, 180),
                nrow = 2, ncol = 3, byrow = TRUE)

rownames(sales) <- c("North", "South")
colnames(sales) <- c("Jan", "Feb", "Mar")

print(sales)
#        Jan  Feb  Mar
# North  100  200  150
# South  300  250  180

sales["North", "Feb"]   # 200

Matrix Arithmetic

A <- matrix(c(1,2,3,4), nrow=2)
B <- matrix(c(5,6,7,8), nrow=2)

A + B    # element-wise addition
A * B    # element-wise multiplication
A %*% B  # TRUE matrix multiplication (dot product)
t(A)     # transpose (flip rows and columns)

Useful Matrix Functions

Function       Description
──────────────────────────────────────────────────
det(m)         Determinant
solve(m)       Inverse of a matrix
t(m)           Transpose
rbind(m1, m2)  Add rows from m2 below m1
cbind(m1, m2)  Add columns from m2 to right of m1
apply(m,1,fn)  Apply function to each row (margin=1)
apply(m,2,fn)  Apply function to each column (margin=2)
# Row and column sums
sales_matrix <- matrix(c(100,200,150,300,250,180), nrow=2, byrow=TRUE)
rowSums(sales_matrix)     # 450 730
colSums(sales_matrix)     # 400 450 330
rowMeans(sales_matrix)    # 150 243.33
colMeans(sales_matrix)    # 200 225 165

Matrices appear in statistics (correlation matrices, covariance matrices), data science (feature matrices for machine learning), and image processing (images are stored as pixel value matrices). Mastering matrix indexing and operations prepares you for linear algebra tasks in R.

Leave a Comment

Your email address will not be published. Required fields are marked *