Matrix in R
In R programming, a matrix is a two-dimensional data structure arranged in rows and columns. Every element in an R matrix must have the same atomic type, such as numeric, character, or logical.
Matrices are commonly used for numerical calculations, linear algebra, statistical computing, and data transformations. This tutorial explains how to create an R matrix, inspect its dimensions, access rows and columns, and perform matrix arithmetic.
Create a Matrix in R with matrix()
Use the matrix() function to create a matrix from a vector. The main arguments are data, nrow, ncol, and byrow.
matrix(data, nrow, ncol, byrow = FALSE, dimnames = NULL)
By default, R fills a matrix column by column. Set byrow = TRUE to fill it row by row.
M1 <- matrix(1:12, nrow = 4, ncol = 3)
M1
[,1] [,2] [,3]
[1,] 1 5 9
[2,] 2 6 10
[3,] 3 7 11
[4,] 4 8 12
The same values can be arranged row by row as follows.
M2 <- matrix(1:12, nrow = 4, ncol = 3, byrow = TRUE)
M2
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
[4,] 10 11 12
Check R Matrix Dimensions and Type
Use dim(), nrow(), and ncol() to inspect the shape of a matrix. Use is.matrix() to check whether an object is a matrix.
dim(M1)
nrow(M1)
ncol(M1)
is.matrix(M1)
[1] 4 3
[1] 4
[1] 3
[1] TRUE
Because a matrix can contain only one atomic type, R may coerce values when different types are combined. For example, adding a character value to a numeric matrix converts all elements to character values.
R Matrix Tutorials
- R – Create Matrix
- R – Check if R Object is a Matrix
- R – Get Element at Given Row, Column of Matrix
- R – Get Specific Row of Matrix
- R – Get Specific Column of Matrix
- R – Get Multiple Rows of Matrix
- R – Get Multiple Columns of Matrix
- R – Matrix Multiplication
- R – Transpose Matrix
- R – Inverse Matrix
- R – Correlation Matrix
Access Elements, Rows, and Columns of an R Matrix
Use square brackets with row and column indexes to access matrix values. R indexes start at 1.
MatrixName[row_index, column_index]
The following example selects the element in row 3 and column 2.
> M1
[,1] [,2] [,3]
[1,] 1 5 9
[2,] 2 6 10
[3,] 3 7 11
[4,] 4 8 12
> M1[3,2]
[1] 7
If the row index is omitted and the column index is provided, R returns the complete column.
> M1
[,1] [,2] [,3]
[1,] 1 5 9
[2,] 2 6 10
[3,] 3 7 11
[4,] 4 8 12
> M1[,2]
[1] 5 6 7 8
M1[,2] selects the second column of the matrix M1.
If the row index is provided and the column index is omitted, R returns the complete row.
> M1
[,1] [,2] [,3]
[1,] 1 5 9
[2,] 2 6 10
[3,] 3 7 11
[4,] 4 8 12
> M1[3,]
[1] 3 7 11
M1[3,] selects the third row of the matrix M1.
When a single row or column is selected, R usually simplifies the result to a vector. Use drop = FALSE when the result must remain a matrix.
M1[3, , drop = FALSE]
M1[, 2, drop = FALSE]
Assign Row Names and Column Names to an R Matrix
Meaningful row and column names make matrix output easier to read. Use rownames() and colnames(), or pass names through the dimnames argument of matrix().
scores <- matrix(
c(78, 84, 91, 73, 88, 95),
nrow = 2,
byrow = TRUE
)
rownames(scores) <- c("Student_A", "Student_B")
colnames(scores) <- c("Math", "Science", "English")
scores
Math Science English
Student_A 78 84 91
Student_B 73 88 95
Add and Subtract R Matrices
Use the + operator to add two matrices element by element. Both matrices must have the same number of rows and columns.
> M1
[,1] [,2] [,3]
[1,] 1 5 9
[2,] 2 6 10
[3,] 3 7 11
[4,] 4 8 12
> M2
[,1] [,2] [,3]
[1,] 5 9 13
[2,] 6 10 14
[3,] 7 11 15
[4,] 8 12 16
> M3 = M1 + M2
> M3
[,1] [,2] [,3]
[1,] 6 14 22
[2,] 8 16 24
[3,] 10 18 26
[4,] 12 20 28
Use the - operator to subtract corresponding elements. The matrices must again have matching dimensions.
> M2
[,1] [,2] [,3]
[1,] 5 9 13
[2,] 6 10 14
[3,] 7 11 15
[4,] 8 12 16
> M1
[,1] [,2] [,3]
[1,] 1 5 9
[2,] 2 6 10
[3,] 3 7 11
[4,] 4 8 12
> M3 = M2 - M1
> M3
[,1] [,2] [,3]
[1,] 4 4 4
[2,] 4 4 4
[3,] 4 4 4
[4,] 4 4 4
>
Element-wise R Matrix Multiplication with *
Use the * operator to multiply corresponding elements of two matrices. This is element-wise multiplication, not linear algebra matrix multiplication.
> M1
[,1] [,2] [,3]
[1,] 1 5 9
[2,] 2 6 10
[3,] 3 7 11
[4,] 4 8 12
> M2
[,1] [,2] [,3]
[1,] 5 9 13
[2,] 6 10 14
[3,] 7 11 15
[4,] 8 12 16
> M3 = M1*M2
> M3
[,1] [,2] [,3]
[1,] 5 45 117
[2,] 12 60 140
[3,] 21 77 165
[4,] 32 96 192
>
R Matrix Multiplication with %*%
For linear algebra matrix multiplication, use the %*% operator. If matrix A has dimensions m × n, matrix B must have dimensions n × p. The result has dimensions m × p.
A <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, byrow = TRUE)
B <- matrix(c(7, 8, 9, 10, 11, 12), nrow = 3, byrow = TRUE)
A %*% B
[,1] [,2]
[1,] 58 64
[2,] 139 154
The operators * and %*% are not interchangeable. Use * for corresponding elements and %*% for row-by-column multiplication.
Element-wise R Matrix Division
Use the / operator to divide each element of one matrix by the corresponding element of another matrix. The matrices should have matching dimensions.
> M1
[,1] [,2] [,3]
[1,] 1 5 9
[2,] 2 6 10
[3,] 3 7 11
[4,] 4 8 12
> M2
[,1] [,2] [,3]
[1,] 5 9 13
[2,] 6 10 14
[3,] 7 11 15
[4,] 8 12 16
> M3 = M2/M1
> M3
[,1] [,2] [,3]
[1,] 5.000000 1.800000 1.444444
[2,] 3.000000 1.666667 1.400000
[3,] 2.333333 1.571429 1.363636
[4,] 2.000000 1.500000 1.333333
>
Transpose an R Matrix
Use t() to transpose a matrix. The rows of the original matrix become columns, and the columns become rows.
A <- matrix(1:6, nrow = 2)
t(A)
[,1] [,2]
[1,] 1 2
[2,] 3 4
[3,] 5 6
R Matrix vs Data Frame
An R matrix stores values in two dimensions, but all elements must share one atomic type. A data frame can store different types in different columns, such as numeric values in one column and character values in another.
- Use a matrix for homogeneous numeric calculations and linear algebra.
- Use a data frame for table-like datasets with columns of different types.
- Use
as.matrix()to convert a compatible data frame to a matrix. - Use
as.data.frame()to convert a matrix to a data frame.
Common R Matrix Errors and How to Avoid Them
- Non-conformable arguments: Check matrix dimensions before using
%*%. - Unexpected character values: Combining character and numeric values causes type coercion.
- Vector returned instead of matrix: Add
drop = FALSEwhile selecting one row or column. - Wrong fill direction: Remember that
matrix()fills columns by default unlessbyrow = TRUE. - Confusing * with %*%: Use
*for element-wise multiplication and%*%for matrix multiplication.
R Matrix FAQs
How do I create a matrix in R?
Use matrix(data, nrow, ncol). Add byrow = TRUE when values should be filled row by row instead of column by column.
What is the difference between * and %*% in R matrices?
The * operator multiplies corresponding elements. The %*% operator performs linear algebra matrix multiplication.
How do I select a complete row or column from an R matrix?
Use M[row, ] for a row and M[, column] for a column. Add drop = FALSE to keep the result as a matrix.
Can an R matrix contain numbers and text together?
A matrix can contain only one atomic type. If numeric and character values are combined, R coerces all values to character.
How is an R matrix different from a data frame?
A matrix requires one atomic type for all elements. A data frame can use a different type for each column.
R Matrix Editorial QA Checklist
- Confirm that examples distinguish element-wise multiplication with
*from matrix multiplication with%*%. - Verify that matrix dimensions are compatible in every
%*%example. - Check that row and column indexes use R’s one-based indexing.
- Confirm that examples describe column-wise filling as the default behavior of
matrix(). - Ensure that matrix and data-frame differences are explained without implying that either structure is always preferable.
Summary of R Matrix Operations
In this R tutorial, we learned how to create an R matrix, inspect its dimensions, access rows and columns, assign names, and perform element-wise and linear algebra operations. Use matrices when data is two-dimensional and all values share the same atomic type.
TutorialKart.com