Problem 1: (50 points)
- Create a 4 by 5 matrix of the numbers 1:20 called
M by
specifying the nrow and byrow = TRUE arguments
in the matrix fucntion.
M <- matrix(1:20, nrow = 4, byrow = TRUE)
M
## [,1] [,2] [,3] [,4] [,5]
## [1,] 1 2 3 4 5
## [2,] 6 7 8 9 10
## [3,] 11 12 13 14 15
## [4,] 16 17 18 19 20
- Using indexing notation, grab first two rows of
M
M[1:2, ]
## [,1] [,2] [,3] [,4] [,5]
## [1,] 1 2 3 4 5
## [2,] 6 7 8 9 10
- using indexing notation, grab first and third columns of
M
M[, c(1, 3)]
## [,1] [,2]
## [1,] 1 3
## [2,] 6 8
## [3,] 11 13
## [4,] 16 18
- Create vector
V = c(21, 22, 23, 24, 25)
V <- c(21, 22, 23, 24, 25)
V
## [1] 21 22 23 24 25
- Use
rbind function to create a matrix B
using the matrix M and the vector V
B <- rbind(M, V)
- Confirm that
B is a matrix
is.matrix(B)
## [1] TRUE
Problem 2: (50 points)
- Create a 3 by 5 matrix of the numbers
11:25 calledNby specifying thenrowandbyrow
= FALSEarguments in thematrix` function.
N <- matrix(11:25, nrow = 3, byrow = FALSE)
N
## [,1] [,2] [,3] [,4] [,5]
## [1,] 11 14 17 20 23
## [2,] 12 15 18 21 24
## [3,] 13 16 19 22 25
- Write a R code to extract the sub_matrix of N whose 4th column
values are grater than 20
subN <- N[N[, 4] > 20, , drop = FALSE]
subN
## [,1] [,2] [,3] [,4] [,5]
## [1,] 12 15 18 21 24
## [2,] 13 16 19 22 25