- Create a matrix named
m1with three rows and five columns and all the numeric (integer) values from 6 to 20!
Click here to see the answer
m1 <- matrix(6:20, nrow = 3, ncol = 5)
m1
## [,1] [,2] [,3] [,4] [,5]
## [1,] 6 9 12 15 18
## [2,] 7 10 13 16 19
## [3,] 8 11 14 17 20- Multiply all elements in
m1by 0.5! Overwrite the matrixm1with the result!
Click here to see the answer
m1 <- m1 * 0.5- Create another matrix
m2with one row and five columns and all the numeric (integer) values from 1 to 5!
Click here to see the answer
m2 <- matrix(1:5, nrow = 1, ncol = 5)
m2
## [,1] [,2] [,3] [,4] [,5]
## [1,] 1 2 3 4 5- Calculate the sum of all elements in
m2!
Click here to see the answer
sum(m2)
## [1] 15- Combine
m1andm2withrbing(). Save the result asm3and check the dimension of the new matrix!
Click here to see the answer
m3 <- rbind(m1, m2)
m3
## [,1] [,2] [,3] [,4] [,5]
## [1,] 3.0 4.5 6.0 7.5 9.0
## [2,] 3.5 5.0 6.5 8.0 9.5
## [3,] 4.0 5.5 7.0 8.5 10.0
## [4,] 1.0 2.0 3.0 4.0 5.0
dim(m3)
## [1] 4 5- Index the 5th column of
m3!
Click here to see the answer
m3[ , 5]
## [1] 9.0 9.5 10.0 5.0- Index the 2nd and 4th lines of
m3!
Click here to see the answer
m3[ c(2, 4), ]
## [,1] [,2] [,3] [,4] [,5]
## [1,] 3.5 5 6.5 8 9.5
## [2,] 1.0 2 3.0 4 5.0- Calculate the sums for all columns in
m3!
Click here to see the answer
colSums(m3)
## [1] 11.5 17.0 22.5 28.0 33.5- Calculate the standard deviation for the 3rd column in
m3!
Click here to see the answer
sd( m3[ , 3] )
## [1] 1.796988- From
m3, index the element in the 2nd column and 2nd line and all eight adjacent elements! Save the result asm4and examine its object class!
Click here to see the answer
m4 <- m3[2:4, 2:4]
m4
## [,1] [,2] [,3]
## [1,] 5.0 6.5 8.0
## [2,] 5.5 7.0 8.5
## [3,] 2.0 3.0 4.0
class(m4)
## [1] "matrix"