## Exercise 2. Numeric vector manipulation # Create the script "exercise2.R" and save it to the "Rintro/day1" directory: # you will save all the commands of exercise 2 in that script. # 1. Go to Rintro/day1 # First check where you currently are with getwd(); # then go to Rintro/day1 with setwd() getwd() setwd("Rintro/day1") setwd("/users/bi/sbonnin/Rintro/day1") # 2. Create a numeric vector y from 2 to 11 included. # Show y in the console. y <- c(2, 3, 4, 5, 6, 7, 8, 9, 10, 11) y <- 2:11 # 3. How many elements are in y? I.e what is the length of vector y? length(y) # 4. Show the 2nd element of y. y[2] # 5. Show the 3rd and the 6th elements of y. y[c(3,6)] # 6. Remove the 4th element of y: reassign. Check the length of y. y <- y[-4] # 7. Show all elements of y that are inferior to 7. y[ y < 7 ] # 8. Show all elements of y that are # superior or equal to 4 and inferior to 9 y[ y >= 4 & y < 9 ] # 9. Show all elements of y that are # either inferior to 4, or superior to 9. y[ y < 4 | y > 9 ] # 10. Create the vector x of 1000 random numbers # from the normal distribution: # First read the help page of rnorm() function. x <- rnorm(1000) # 11. What are the mean, median, minimum and maximum values of x? mean(x); median(x); min(x); max(x) # 12. Run the summary() function on x. # What additional information to you obtain? summary(x) # 13. Create vector y2: y2 <- c(1, 11, 5, 62, 18, 2, 8) # 14. What is the sum of all elements in y2? sum(y2) # 15. Which elements of y2 are present in y? # Note: remember %in%. y2[ y2 %in% y ] # 16. Multiply each element of y2 by 1.5: reassign. y2 <- y2 * 1.5 # 17. Use the function any() to check if the number 3 is present. any( y2 == 3 ) ## Exercise 2b. OPTIONAL # 1. Create vector myvector: myvector <- c(1, 2, 3, 1, 2, 3, 1, 2, 3) # Create the same vector using the rep() function (?rep) myvector <- rep(1:3, 3) # 2. Replace the values at the 5th, 6th and 7th position # in myvector with 8, 12 and 32. myvector[5:7] <- c(8, 12, 32) # 3. Calculate the fraction/percentage of each element of # myvector relative to the total sum of the vector. # sum() can be useful. mytotal <- sum(myvector) myvector / mytotal (myvector / mytotal) * 100 # 4. Add vector c(2, 4, 6, 7) after the last element of myvector: reassign! newvector <- c(2, 4, 6, 7) myvector <- c(myvector, newvector)