9.2 Exercise 2. Numeric vector manipulation
9.2.1 Exercise 2a.
Create the script “exercise2.R” and save it to the “Rcourse/Module1” directory: you will save all the commands of exercise 2 in that script.
Remember you can comment the code using #.
1- Go to Rcourse/Module1 First check where you currently are with getwd(); then go to Rcourse/Module1 with setwd()
2- Create a numeric vector y which contains the numbers from 2 to 11, both included.
Show y in the terminal.
correction
## [1] 2 3 4 5 6 7 8 9 10 11
3- How many elements are in y? I.e what is the length of vector y ?
4- Show the 2nd element of y.
5- Show the 3rd and the 6th elements of y.
6- Remove the 4th element of y: reassign. What is now the length of y ?
7- Show all elements of y that are less than 7.
correction
## [1] TRUE TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE
## [1] 2 3 4 6
8- Show all elements of y that are greater or equal to 4 and less than 9.
9- Create the vector x of 1000 random numbers from the normal distribution:
First read the help page of the rnorm() function.
correction
10. What are the mean, median, minimum and maximum values of x?
correction
## [1] -0.01871379
## [1] -0.02276918
## [1] -3.412708
## [1] 3.348919
11- Run the summary() function on x.
What additional information do you obtain ?
correction
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## -3.41271 -0.63370 -0.02277 -0.01871 0.63355 3.34892
12- Create vector y2 as:
13. What is the sum of all elements in y2 ?
14- Which elements of y2 are also present in y ?
Note: remember the %in% operator.
15- Multiply each element of y2 by 1.5: reassign.
correction
16- Use the function any() to check if the number 3 is present.
correction
## [1] TRUE
9.2.2 Exercise 2b.
1- Create the vector myvector as:
Create the same vector using the rep() function (?rep)
correction
2- Reassign the 5th, 6th and 7th position of myvector with the values 8, 12 and 32, respectively.
correction
3- Calculate the fraction/percentage of each element of myvector (relative to the sum of all elements of the vector).
sum() can be useful.
correction
# sum of all elements of the vector
mytotal <- sum(myvector)
# divide each element by the sum
myvector / mytotal
## [1] 0.015625 0.031250 0.046875 0.015625 0.125000 0.187500 0.500000 0.031250
## [9] 0.046875
## [1] 1.5625 3.1250 4.6875 1.5625 12.5000 18.7500 50.0000 3.1250 4.6875
4- Add vector c(2, 4, 6, 7) to myvector (combining both vectors): reassign!
correction
# create the new vector
newvector <- c(2, 4, 6, 7)
# combine both myvector and newvector
c(myvector, newvector)
## [1] 1 2 3 1 8 12 32 2 3 2 4 6 7