## 9.2 Exercise 2. Numeric vector manipulation (15 minutes)

### 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()

``````getwd()
setwd("Rcourse/Module1")
setwd("~/Rcourse/Module1")``````

2- Create a numeric vector “y” which contains the numbers from 2 to 11, both included.
Show y in the console.

``````y <- c(2, 3, 4, 5, 6, 7, 8, 9, 10, 11)
# same as
y <- 2:11
# show in console:
y``````
``##    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 ?

``length(y)``
``##  10``

4- Show the 2nd element of y.

``y``
``##  3``

5- Show the 3rd and the 6th elements of y.

``y[c(3,6)]``
``##  4 7``

6- Remove the 4th element of y: reassign. What is now the length of y ?

``````# remove 4th element and reassign
y <- y[-4]
# length of y
length(y)``````
``##  9``

7- Show all elements of y that are less than 7.

``````# which elements of y are less than 7:
y < 7``````
``##   TRUE  TRUE  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE``
``````# show those elements
y[ y < 7 ]``````
``##  2 3 4 6``

8- Show all elements of y that are more than or equal to 4 and less than 9.

``y[ y >= 4 & y < 9 ]``
``##  4 6 7 8``

9. What are the mean, median, minimum and maximum values of y?

``mean(y); median(y); min(y); max(y)``
``##  6.666667``
``##  7``
``##  2``
``##  11``

10- Create vector y2 as:

``y2 <- c(1, 11, 5, 62,  18, 2, 8)``

11- Which elements of y2 are also present in y ?
Note: remember the %in% operator.

``y2[ y2 %in% y ]``
``##  11  2  8``

### 9.2.2 Exercise 2b.

1- Create the vector myvector as:

``myvector <- c(1, 2, 3, 1, 2, 3, 1, 2, 3)``

2- Create the same vector using the rep.int() function (look for help: ?rep.int)

``myvector <- rep.int(x=1:3, times=3)``

3- Calculate the fraction/percentage of each element of myvector (relative to the sum of all elements of the vector).
Note: function sum() can be useful…

``````# sum of all elements of the vector
``##  0.05555556 0.11111111 0.16666667 0.05555556 0.11111111 0.16666667 0.05555556 0.11111111 0.16666667``
``````# multiply by 100 to get a percentage
``##   5.555556 11.111111 16.666667  5.555556 11.111111 16.666667  5.555556 11.111111 16.666667``