## What is a Matrix

A matrix in mathematics is a two-dimensional array of numbers, symbols, or expressions arranged in rows and columns. In R, matrices are an essential data structure for handling and processing tabular data. Each element in a matrix is uniquely identified by its row and column position.

## How to Create Matrices

syntax

To create a matrix in R, we use the ** matrix()** fuction. The matrix function accepts 2 arguments, the first is the vector. The second argument is the # columns and/or #rows.

Example 1

x <- c(1,2,3,4)

x.mat <- matrix(x, nrow=2, ncol=2, byrow=TRUE)

print(x.mat)

> x.mat <- matrix(x, nrow=2, ncol=2, byrow=TRUE) > x.mat

[,1] [,2]

[1,] 1 2

[2,] 3 4

Example 2

# Create a matrix

my_matrix <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3, byrow= TRUE)

# Print the matrix

print(my_matrix)

# Print the matrix

> print(my_matrix)

[,1] [,2] [,3]

[1,] 1 3 5

[2,] 2 4 6

By default, it will arrange the matrix by the number of rows first. If by row is set to false, it will arrange the columns first.

You can also choose to specify the number of columns (ncol = ) instead of the number of rows (nrow = ).

my_colmatrix <- matrix(c(3:8), ncol = 2)

print(my_colmatrix)

> print(my_colmatrix)

[,1] [,2]

[1,] 3 6

[2,] 4 7

[3,] 5 8

You can see that the first, 2 colums are created. R infers the number of rows automatically.