## Exercise 1. Numeric vector manipulation
# First create a script “exercise1.R” and save it to the “Rintro/day1” directory: you will save all your commands in it for that exercise.
# Remember you can comment the code using #.
# 1. Create vector y as:
y <- 8:22
# 2. How many elements does y contain?
length(y)
# 3. Remove the 7th element of y.
y[-7]
y <- y[-7]
# 4. Select all elements of y that are inferior to 12.
# * First get the logical vector: y < 12
y < 12
# * Then get the actual values: y[ ? ]
y[y < 12]
# 5. Select all elements of y that are equal to 22.
y[y == 22]
# 6. Select all elements of y that are superior to 12
# and inferior to 18, both included.
y[ y >= 12 & y <= 18 ]
# 7. Select all elements of y that are either
# inferior to 10, or superior to 20.
y[ y < 10 | y > 20 ]
# 8. Create vector x of 1000 random numbers from the normal distribution:
# First read the help page of rnorm function.
x <- rnorm(1000)
# 9. What are the mean, median, minimum and maximum values of x?
mean(x); median(x); min(x); max(x)
# 10. What additional information do you get with the summary() function?
summary(x)
# 11. Create vector y2 as:
y2 <- c(1, 11, 130, 62, 18, 2, 37)
# 12. Which elements of y2 are present in y?
# Note: remember %in%.
y2 %in% y
y2[y2 %in% y]
# 13. Add 2 to each element of y2: reassign the new values to the y2 object!
y2 + 2
y2 <- y2 + 2
## OPTIONAL ##
# 14. Create vector myvector such as:
# * Create it the way shown above.
myvector <- c(1, 2, 3, 1, 2, 3, 1, 2, 3)
# * Create the same vector using the rep function.
myvector <- rep(c(1, 2, 3), 3)
# 15. Replace the 5th, 6th and 7th element of myvector with 8, 12 and 32 values.
myvector[5:7] <- c(8, 12, 32)
# 16. Calculate the fraction/percentage of each element of myvector relative to the total sum of the vector.
# sum() can be useful.
myvector/sum(myvector)*100
# 17. Add vector c(2, 4, 6, 7) to the end of myvector: reassign!
myvector <- c(myvector, c(2, 4, 6, 7))