R Matrices
R matrices (singular: matrix) are a rectangular array of numbers, symbols, or expressions, arranged in rows and columns. It has two dimensional structure. All columns in a matrix are of the same type and of the same length.
Create a matrix
R provides matrix() function to create a matrix. The number of rows and columns of the matrix are assigned in nrow and ncol and by default it is generated column wise. To make it arrange in row wise, pass byrow=TRUE argument in the matrix() function.
A = matrix(c(4,3,5,7,2,5), nrow=2, ncol=3, byrow=TRUE)
A
[,1] [,2] [,3]
[1,] 4 3 5
[2,] 7 2 5
The above matrix have 2 number of rows and 3 number of columns as we pass nrow=2 and ncol=3.
If we want to give some name to rows and columns of the matrix, then it is also possible with dimnames argument. Dimnames contain names of rows and columns in the list.
M = matrix(c(4,3,5,7,2,5),nrow=2,ncol=3,byrow=TRUE,
+ dimnames=list(c('x','y'),c('a','b','c')))
print(M)
a b c
x 4 3 5
y 7 2 5
Access and modify dimnames
R provide colnames() and rownames() functions to access and change the dimnames values. The below code returns the columns and rows dimnames of matrix M.
colnames(M)
[1] "a" "b" "c"
rownames(M)
[1] "x" "y"
Access matrix element
In the matrix, we can access elements by using the column and row indexes.
The following command accesses all elements of the second row.
M[2,]
a b c
7 2 5
, the following command accesses all elements of the first column.
M[,1]
x y
4 7
and the following command accesses element at second row and the third column.
M[2,3]
[1] 5
Arithmatic Operations on Matrices
We can perform arithmetic operations on matrices of the same dimensions and the result of the operation is also a matrix. Here, we have generated two matrices of same rows and columns and perform addition, subtraction, multiplication and division operations on them.
M1 = matrix(c(4,3,5,7,2,5),nrow=2,ncol=3,byrow=TRUE,
+ dimnames=list(c('x1','y1'),c('a1','b1','c1')))
M2 = matrix(c(5,3,7,2,9,4),nrow=2,ncol=3,byrow=TRUE,
+ dimnames=list(c('x2','y2'),c('a2','b2','c2')))
# Addition
result1 <- M1+M2
print(result1)
#Substraction
result2 <- M1-M2
print(result2)
#Multiplication
result3 <- M1*M2
print(result3)
#Division
result4 <- M1/M2
print(result4)