RCourse-Lecture13-Calculations-Matrix Operations - Row, Column & Other Operations - Watermark
RCourse-Lecture13-Calculations-Matrix Operations - Row, Column & Other Operations - Watermark
Lecture 13
Basics of Calculations
::::
Matrix Operations – Row, Column & Other
Operations
Shalabh
Department of Mathematics and Statistics
Indian Institute of Technology Kanpur
1
Matrix Operations
Renaming the row and column names
> x = matrix( nrow=4, ncol=3, data=c(1:12) )
> x
[,1] [,2] [,3]
[1,] 1 5 9
[2,] 2 6 10
[3,] 3 7 11
[4,] 4 8 12
2
Matrix Operations
Renaming the row and column names
> rownames(x) = c("r1", "r2", "r3", "r4")
> x
[,1] [,2] [,3]
r1 1 5 9
r2 2 6 10
r3 3 7 11
r4 4 8 12
4
Matrix Operations
Assigning a specified number to all matrix elements:
5
Matrix Operations: Diagonal matrix
Construction of a diagonal matrix, here the identity matrix of a
dimension 3:
> d = diag(1, nrow=3, ncol=3)
> d
[,1] [,2] [,3]
[1,] 1 0 0
[2,] 0 1 0
[3,] 0 0 1
6
Matrix Operations: Diagonal matrix
Construction of a diagonal matrix with all numbers as 5 of a
dimension 3:
> d = diag(5, nrow=3, ncol=3)
> d
[,1] [,2] [,3]
[1,] 5 0 0
[2,] 0 5 0
[3,] 0 0 5
7
Matrix Operations: Transpose
Transpose of a matrix X: X’
8
Matrix Operations: Transpose
Transpose of a matrix X: X’
> xt = t(x)
> xt
[,1] [,2] [,3] [,4]
[1,] 1 3 5 7
[2,] 2 4 6 8
9
Matrix Operations: Row and column sums
Finding the row and column sums
> x = matrix(nrow=4, ncol=2, data=c(1,2,3,4,5,6,7,8))
> x
[,1] [,2]
[1,] 1 5
[2,] 2 6
[3,] 3 7
[4,] 4 8
10
Matrix Operations: Row and column means
> x
[,1] [,2]
[1,] 1 5 (1+5) = 6
[2,] 2 6 (2+6) = 8
[3,] 3 7 (3+7) = 10
[4,] 4 8 (4+8) = 12
(1+2+3+4) (5+6+7+8)
= 10 = 26
> rowSums(x)
[1] 6 8 10 12
> colSums(x)
[1] 10 26 11
Matrix Operations: Row and column means
Finding the row and column means
> x = matrix(nrow=4, ncol=2, data=c(1,2,3,4,5,6,7,8))
> x
[,1] [,2]
[1,] 1 5
[2,] 2 6
[3,] 3 7
[4,] 4 8
12
Matrix Operations: Row and column means
> x
[,1] [,2]
[1,] 1 5 (1+5)/2 = 3
[2,] 2 6 (2+6)/2 = 4
[3,] 3 7 (3+7)/2 = 5
[4,] 4 8 (4+8)/2 = 6
(1+2+3+4)/4 (5+6+7+8)/4
= 2.5 = 6.5
> rowMeans(x)
[1] 3 4 5 6
> colMeans(x)
[1] 2.5 6.5
13