R Matrix
In R, a two-dimensional rectangular data set is known as a matrix. A matrix is created with the help of the vector input to the matrix function. On R matrices, we can perform addition, subtraction, multiplication, and division operation.
In the R matrix, elements are arranged in a fixed number of rows and columns. The matrix elements are the real numbers. In R, we use matrix function, which can easily reproduce the memory representation of the matrix. In the R matrix, all the elements must share a common basic type.
Example
matrix1<-matrix(c(11, 13, 15, 12, 14, 16),nrow =2, ncol =3, byrow = TRUE)
matrix1
Output
[,1] [,2] [,3] [1,] 11 13 15 [2,] 12 14 16
History of matrices in R
The word “Matrix” is the Latin word for womb which means a place where something is formed or produced. Two authors of historical importance have used the word “Matrix” for unusual ways. They proposed this axiom as a means to reduce any function to one of the lower types so that at the “bottom” (0order) the function is identical to its extension.
Any possible function other than a matrix from the matrix holds true with the help of the process of generalization. It will be true only when the proposition (which asserts function in question) is true. It will hold true for all or one of the value of argument only when the other argument is undetermined.
How to create a matrix in R?
Like vector and list, R provides a function which creates a matrix. R provides the matrix() function to create a matrix. This function plays an important role in data analysis. There is the following syntax of the matrix in R:
matrix(data, nrow, ncol, byrow, dim_name)
data
The first argument in matrix function is data. It is the input vector which is the data elements of the matrix.
nrow
The second argument is the number of rows which we want to create in the matrix.
ncol
The third argument is the number of columns which we want to create in the matrix.
byrow
The byrow parameter is a logical clue. If its value is true, then the input vector elements are arranged by row.
dim_name
The dim_name parameter is the name assigned to the rows and columns.
Let’s see an example to understand how matrix function is used to create a matrix and arrange the elements sequentially by row or column.
Example
#Arranging elements sequentially by row. P <- matrix(c(5:16), nrow = 4, byrow = TRUE) print(P) # Arranging elements sequentially by column. Q <- matrix(c(3:14), nrow = 4, byrow = FALSE) print(Q) # Defining the column and row names. row_names = c("row1", "row2", "row3", "row4") ccol_names = c("col1", "col2", "col3") R <- matrix(c(3:14), nrow = 4, byrow = TRUE, dimnames = list(row_names, col_names)) print(R)
Output
[,1] [,2] [,3] [1,] 5 6 7 [2,] 8 9 10 [3,] 11 12 13 [4,] 14 15 16 [,1] [,2] [,3] [1,] 3 7 11 [2,] 4 8 12 [3,] 5 9 13 [4,] 6 10 14 col1 col2 col3 row1 3 4 5 row2 6 7 8 row3 9 10 11 row4 12 13 14