matrix formation

matrix1<-matrix(1:12,byrow = TRUE,nrow=4)
print(matrix1)
##      [,1] [,2] [,3]
## [1,]    1    2    3
## [2,]    4    5    6
## [3,]    7    8    9
## [4,]   10   11   12

row and column names

rwnm<-c('x','y','z','z1')
clnm<-c('a','b','c')
colnames(matrix1)<-clnm
rownames(matrix1)<-rwnm
print(matrix1)
##     a  b  c
## x   1  2  3
## y   4  5  6
## z   7  8  9
## z1 10 11 12
# another way 
matrix(1:12, nrow=4,ncol = 3,byrow = TRUE, dimnames=list(c('row1','row2','row3','row4'),c('c1','c2','c3')))
##      c1 c2 c3
## row1  1  2  3
## row2  4  5  6
## row3  7  8  9
## row4 10 11 12

row wise and column wise sum

rowSums(matrix1)
##  x  y  z z1 
##  6 15 24 33
colSums(matrix1)
##  a  b  c 
## 22 26 30
matrix1*2
##     a  b  c
## x   2  4  6
## y   8 10 12
## z  14 16 18
## z1 20 22 24
matrix1/2
##      a   b   c
## x  0.5 1.0 1.5
## y  2.0 2.5 3.0
## z  3.5 4.0 4.5
## z1 5.0 5.5 6.0

matrix multiplication

a=matrix(1:6, byrow=TRUE, nrow=2)
b=matrix(1:9,byrow = TRUE, nrow=3)
 a%*%b
##      [,1] [,2] [,3]
## [1,]   30   36   42
## [2,]   66   81   96
 a%o%b
## , , 1, 1
## 
##      [,1] [,2] [,3]
## [1,]    1    2    3
## [2,]    4    5    6
## 
## , , 2, 1
## 
##      [,1] [,2] [,3]
## [1,]    4    8   12
## [2,]   16   20   24
## 
## , , 3, 1
## 
##      [,1] [,2] [,3]
## [1,]    7   14   21
## [2,]   28   35   42
## 
## , , 1, 2
## 
##      [,1] [,2] [,3]
## [1,]    2    4    6
## [2,]    8   10   12
## 
## , , 2, 2
## 
##      [,1] [,2] [,3]
## [1,]    5   10   15
## [2,]   20   25   30
## 
## , , 3, 2
## 
##      [,1] [,2] [,3]
## [1,]    8   16   24
## [2,]   32   40   48
## 
## , , 1, 3
## 
##      [,1] [,2] [,3]
## [1,]    3    6    9
## [2,]   12   15   18
## 
## , , 2, 3
## 
##      [,1] [,2] [,3]
## [1,]    6   12   18
## [2,]   24   30   36
## 
## , , 3, 3
## 
##      [,1] [,2] [,3]
## [1,]    9   18   27
## [2,]   36   45   54
t(a)
##      [,1] [,2]
## [1,]    1    4
## [2,]    2    5
## [3,]    3    6
c<-matrix(5:8, ncol = 1,dimnames = list(c('x','y','z','z1'),c('newcol')))
cbind(matrix1,c)
##     a  b  c newcol
## x   1  2  3      5
## y   4  5  6      6
## z   7  8  9      7
## z1 10 11 12      8
diag(c)
## [1] 5
is.matrix(c)
## [1] TRUE

select and indexing

matrix1
##     a  b  c
## x   1  2  3
## y   4  5  6
## z   7  8  9
## z1 10 11 12
# matrix[row,col]
matrix1[1,]
## a b c 
## 1 2 3
matrix1[,2]
##  x  y  z z1 
##  2  5  8 11
# 2 for column , 1 for row 
apply(matrix1,2,sum)
##  a  b  c 
## 22 26 30