A matrix in R is a two-dimensional data structure that contains elements of the same data type arranged in rows and columns. It is a special case of a vector.
Use the matrix()
function:
# Create a 2x3 matrix m <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3) # Output: # [,1] [,2] [,3] # [1,] 1 3 5 # [2,] 2 4 6
By default, R fills matrices column-wise.
m <- matrix(1:6, nrow = 2, byrow = TRUE) # Now elements are filled row-wise.
m[1, 2]
→ Element at 1st row, 2nd columnm[ ,2]
→ Entire 2nd columnm[1, ]
→ Entire 1st rowBasic operations can be done element-wise or using matrix math:
a <- matrix(1:4, nrow=2) b <- matrix(5:8, nrow=2) a + b # Matrix addition a * b # Element-wise multiplication a %*% b # Matrix multiplication (dot product) t(a) # Transpose
rownames(m) <- c("Row1", "Row2") colnames(m) <- c("Col1", "Col2", "Col3")
This helps when accessing elements like: m["Row1", "Col2"]
dim(m)
– get dimensions (rows, cols)nrow(m)
, ncol(m)
– get row or column countlength(m)
– total number of elementssum(m)
, mean(m)
– calculate total and averagematrix()
to create them.[row, column]
syntax.Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!