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. Repeat the same using the byrow=TRUE parameter: what is different?
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
correction
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
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
10- Replace all elements of mat2 that are equal to 2017 with 2018.
correction
11- Multiply all elements of the 2nd column of mat2 by 7. Reassign mat2!
correction
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
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.
- Retrieve the minimum of all columns simultaneously using the apply() function.