9.8 Exercise 4. Matrix manipulation
Create the script “exercise4.R” and save it to the “Rcourse/Module1” directory: you will save all the commands of exercise 4 in that script.
Remember you can comment the code using #.
1- Create three numeric vectors x, y, z, each of 4 elements of your choice.
Use rbind() to create a matrix mat (3 rows and 4 columns) out of x, y and z.
correction
2- Create the same matrix now using the matrix function.
correction
3- Add names to mat’s columns: “a”, “b”, “c”, “d”, respectively.
correction
4- Calculate the sum of each row, and the sum of each column
5- Create the matrix mat2 as:
What does function seq() do?
correction
seq generate sequences of numbers. Here, it creates a sequences from 1 to 10 with a step of 2 numbers.
6- What are the dimensions of mat2 (number of rows and number of columns)?
correction
## [1] 5
## [1] 3
## [1] 5 3
7- Add column names to mat2: “day”, “month” and “year”, respectively.
correction
8- Add row names to mat2: letters “A” to “E”
9- Shows row(s) of mat2 where the month column is greater than or equal to 3.
correction
## A B C D E
## 5 4 3 2 1
## A B C D E
## TRUE TRUE TRUE FALSE FALSE
# finally select row(s) where the month columns is greater than or equal to 3
mat2[mat2[,"month"] >= 3,]
## day month year
## A 1 5 2017
## B 3 4 2017
## C 5 3 2017
10- Replace all elements of mat2 that are equal to 2017 with 2018.
correction
## day month year
## A FALSE FALSE TRUE
## B FALSE FALSE TRUE
## C FALSE FALSE TRUE
## D FALSE FALSE TRUE
## E FALSE FALSE TRUE
## [1] 2017 2017 2017 2017 2017
11- Multiply all elements of the 2nd column of mat2 by 7. Reassign mat2!
correction
## A B C D E
## 35 28 21 14 7
12- Add the column named “time” to mat2, that contains values 8, 12, 11, 10, 8. Save in the new object mat3.
13- Replace all elements of mat3 that are less than 3 with NA.
correction
## day month year time
## A TRUE FALSE FALSE FALSE
## B FALSE FALSE FALSE FALSE
## C FALSE FALSE FALSE FALSE
## D FALSE FALSE FALSE FALSE
## E FALSE FALSE FALSE FALSE
## [1] 1
14- Remove rows from mat3 if a NA is present. Save in the new object mat4.
correction
15- Retrieve the smaller value of each column of mat4.
Try different approaches:
- Retrieve the minimum for each column one by one.
correction
## [1] 3
## [1] 7
## [1] 2018
## [1] 8
- Retrieve the minimum of all columns simultaneously using the apply() function.
correction
## day month year time
## 3 7 2018 8