2.2 matrix
2.2 matrix
In R, matrices are two-dimensional (rows x column) that store data. Each element in a matrix
must be of the same data type (all numeric or all character). A matrix is created using the
matrix() function. By default, matrices are constructed column-wise.
x <- matrix(1:6, nrow = 2, ncol = 3) # by default: the element are fill by column-wise
x
Matrices can also be created directly from vectors by adding a dimension attribute dim()
x <- 1:10
x
[1] 1 2 3 4 5 6 7 8 9 10
dim(x) <- c(2, 5) # no of row=2, no of column=5
x
Example;
x<-1:4
y<-10:13
z<-21:24
cbind(x,y,z) rbind(x,y,z)
x y z [,1] [,2] [,3] [,4]
[1,] 1 10 21 x 1 2 3 4
[2,] 2 11 22 y 10 11 12 13
[3,] 3 12 23 z 21 22 23 24
[4,] 4 13 24
Naming the row and column for matrix
Naming the column and row of matrix using colnames() and rownames()
AA<-matrix(10:30, ncol=3)
AA
colnames(AA)<-c("var1","var2","var3")
AA
rownames(AA)<-c("p1","p2","p3","p4","p5","p6","p7")
AA
M<-matrix(1:25,ncol=5)
M
[,1] [,2] [,3] [,4] [,5]
[1,] 1 6 11 16 21
[2,] 2 7 12 17 22
[3,] 3 8 13 18 23
[4,] 4 9 14 19 24
[5,] 5 10 15 20 25
Matrix computation
We can perform arithmetic operations on matrices just like vectors, element-wise or using
matrix multiplication.
Note that AA*BB is NOT the usual matrix multiplication. To do the real matrix multiplication,
use %*%
x<-c(70,65,120,140)
dataset<-matrix(x, nrow=2, ncol=2)
rownames(dataset)<-c("male","female")
colnames(dataset)<-c("great","excellent")
dataset
colMeans(dataset)
colSums(dataset)
rowMeans(dataset)
rowSums(dataset)
We can use apply() to apply functions like sum(), mean(), max(), sd(), and more to matrices.
This is helpful for performing operations across specific rows or columns of a matrix. We'll
cover the apply family functions in a later chapter.