To create matrices in R, you can use the matrix()
function. This function allows you to create a matrix by specifying the data, the number of rows, and the number of columns.
In this example,
data
with the values 1:6
, which generates a sequence of numbers from 1 to 6.matrix()
function to create a matrix named mat
. The first argument to matrix()
is the data
vector we just created.nrow
argument, setting it to 2. This means our matrix will have 2 rows.ncol
argument, setting it to 3. This means our matrix will have 3 columns.matrix()
function arranges the data in a column-major order by default, filling the matrix by columns. So, the resulting matrix mat
will look like this:1 3 5
2 4 6
print()
function to display the matrix mat
.data <- 1:6
mat <- matrix(data, nrow = 2, ncol = 3)
print(mat)
[,1] [,2] [,3] [1,] 1 3 5 [2,] 2 4 6
In this example,
data
with the values 1:9
, which generates a sequence of numbers from 1 to 9.matrix()
function to create a matrix named mat
. The first argument to matrix()
is the data
vector we just created.nrow
argument, setting it to 3. This means our matrix will have 3 rows.ncol
argument, setting it to 3. This means our matrix will have 3 columns.byrow
argument and set it to TRUE
to fill the matrix by rows instead of the default column-major order. So, the resulting matrix mat
will look like this:1 2 3
4 5 6
7 8 9
print()
function to display the matrix mat
.data <- 1:9
mat <- matrix(data, nrow = 3, ncol = 3, byrow = TRUE)
print(mat)
[,1] [,2] [,3] [1,] 1 2 3 [2,] 4 5 6 [3,] 7 8 9
In this example,
data
with the values 1:8
, which generates a sequence of numbers from 1 to 8.matrix()
function to create a matrix named mat
. The first argument to matrix()
is the data
vector we just created.nrow
argument, setting it to 4. This means our matrix will have 4 rows.ncol
argument, setting it to 2. This means our matrix will have 2 columns.matrix()
function arranges the data in a column-major order by default, filling the matrix by columns. So, the resulting matrix mat
will look like this:1 5
2 6
3 7
4 8
rownames()
function to assign names to the rows of the matrix, setting them to c("Row1", "Row2", "Row3", "Row4")
.colnames()
function to assign names to the columns of the matrix, setting them to c("Col1", "Col2")
.print()
function to display the matrix mat
with its row and column names.data <- 1:8
mat <- matrix(data, nrow = 4, ncol = 2)
rownames(mat) <- c("Row1", "Row2", "Row3", "Row4")
colnames(mat) <- c("Col1", "Col2")
print(mat)
Col1 Col2 Row1 1 5 Row2 2 6 Row3 3 7 Row4 4 8
In this tutorial, we learned How to Create a Matrix in R language with well detailed examples.