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 #.
Answer
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?
Answer
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)?
Answer
# 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.
Answer
# first row:
mat[1,]
# third column
mat[,3]4- Calculate the sum of each row, and the sum of each column
Answer
rowSums(mat); colSums(mat)5- Add column names to mat: “day,” “month” and “year,” respectively.
Answer
colnames(mat) <- c("day", "month", "year")6- Add row names to mat: letters “A” to “E”
Answer
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.
Answer
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 ?
Answer
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
# element(s) of column day that is/are less than 5
mat[,"day"] < 5
# element(s) of column month that is/are greater than or equal to 3 AND element(s) of column day that is/are less than 5
mat[,"month"] >= 3 & mat[,"day"] < 5
# finally select corresponding rows
mat[mat[,"month"] >= 3 & mat[,"day"] < 5,]