## 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 #.

``````getwd()
setwd("Rcourse/Module1")
setwd("~/Rcourse/Module1")``````

1- Create the matrix mat as:

``mat <- matrix(c(seq(from=1, to=10, by=2), 5:1, rep(x=2020, times=5)), ncol=3)``

What does function seq() do?

seq generate sequences of numbers. Here, it creates a sequences from 1 to 10 with a step of 2 numbers.

2- What are the dimensions of mat (number of rows and number of columns)?

``````# number of rows
nrow(mat)
# number of columns
ncol(mat)
# dimensions: number of rows, number of columns
dim(mat)``````

3- Extract the first row of mat. Then the third column.

``````# first row:
mat[1,]
# third column
mat[,3]``````

4- Calculate the sum of each row, and the sum of each column

``rowSums(mat); colSums(mat)``

5- Add column names to mat: “day,” “month” and “year,” respectively.

``colnames(mat) <- c("day", "month", "year")``

6- Add row names to mat: letters “A” to “E”

``````rownames(mat) <- c("A", "B", "C", "D", "E")
rownames(mat) <- LETTERS[1:5]``````

7- Shows row(s) of mat where the month column is greater than or equal to 3.

Step by step:

``````# select column month
mat[, "month"]
# element(s) of column month that is (are) greater than or equal to 3
mat[,"month"] >= 3
# finally select row(s) where the month columns is greater than or equal to 3
mat[mat[,"month"] >= 3,]``````

8- Shows row(s) of mat where the month column is greater than or equal to 3 AND the day column is less than 5. How many rows are left ?

``````# select column month