## Exercice 4. Matrix manipulation. # First create a script “exercise4.R” and save it to the “Rintro/day2” directory: you will save all your commands in it for that exercise. # 1. Create matrix m as: m <- matrix(c(seq(from=1, to=10, by=2), 5:1, rep(2017, 5)), ncol=3) # 2. What does function seq() do? # 3. What are the dimensions of m (number of rows and number of columns)? dim(m); nrow(m); ncol(m) # 4. Create matrix m2 and m3 as: m2 <- matrix(c(seq(1, 10, 2), 5:1, rep(2017,5)), ncol=3) m3 <- matrix(c(seq(1, 10, 2), 5:1, rep(2017,5)), ncol=3, byrow=T) # Why are m2 and m3 different? # 5. Compute the sum of each row of m3: rowSums(m3) # 6. Add column names "day", "month" and "year" to m2. colnames(m2) <- c("day", "month", "year") # 7. Add row names A to E to m2. rownames(m2) <- c("A", "B","C", "D", "E") rownames(m2) <- toupper(letters[1:5]) rownames(m2) <- LETTERS[1:5] # 8. Select rows of m2 if the month is superior or equal to 3. # Note: there are 2 different ways of doing this: using the column name or using the column index: try both! m2[m2[,2] >= 3,] m2[m2[,"month"] >= 3,] # 9. Replace all elements that are 2017 with 0 in m3. m3[m3==2017] <- 0 # 10. Multiply all elements of the 2d column of m3 by 7. m3[,2]*7 m3[,2] <- m3[,2]*7 # 11. Add one column of 1s to m3: save in m4. m4 <- cbind(m3, 1) # 12. Replace all elements of m4 that are superior to 10 with NA. m4[m4 > 10] <- NA