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 console.
correction
##  [1]  2  3  4  5  6  7  8  9 10 113- 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 inferior to 7.
correction
## [1]  TRUE  TRUE  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE## [1] 2 3 4 68- Show all elements of y that are superior or equal to 4 and inferior to 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.04611927## [1] -0.04431017## [1] -3.032328## [1] 4.07949511- Run the summary() function on x. 
What additional information do you obtain ?
correction
##     Min.  1st Qu.   Median     Mean  3rd Qu.     Max. 
## -3.03233 -0.74507 -0.04431 -0.04612  0.66838  4.0794912- Create vector y2 as:
13- Which elements of y2 are also present in y ?
Note: remember the %in% operator.
14- Multiply each element of y2 by 1.5: reassign.
correction
15- Use the function any() to check if the number 3 is present.
Check the help page of any()!
correction
## [1] TRUE9.2.2 Exercise 2b.
1- Create the vector myvector as:
Create the same vector using the rep.int() function (?rep.int)
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).
Note: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.68754- 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