- Create a matrix named
m1
with three rows and five columns and all the numeric (integer) values from 6 to 20!
Click here to see the answer
<- matrix(6:20, nrow = 3, ncol = 5)
m1
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
m1
by 0.5! Overwrite the matrixm1
with the result!
Click here to see the answer
<- m1 * 0.5 m1
- Create another matrix
m2
with one row and five columns and all the numeric (integer) values from 1 to 5!
Click here to see the answer
<- matrix(1:5, nrow = 1, ncol = 5)
m2
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
m1
andm2
withrbing()
. Save the result asm3
and check the dimension of the new matrix!
Click here to see the answer
<- rbind(m1, m2)
m3
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
5]
m3[ , ## [1] 9.0 9.5 10.0 5.0
- Index the 2nd and 4th lines of
m3
!
Click here to see the answer
c(2, 4), ]
m3[ ## [,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 asm4
and examine its object class!
Click here to see the answer
<- m3[2:4, 2:4]
m4
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"