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

Answer
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.

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

Answer
length(y)
## [1] 10

4- Show the 2nd element of y.

Answer
y[2]
## [1] 3

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

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

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

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

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

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

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

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

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

Answer
mean(y); median(y); min(y); max(y)
## [1] 6.666667
## [1] 7
## [1] 2
## [1] 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.

Answer
y2[ y2 %in% y ]
## [1] 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)

Answer
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…

Answer
# sum of all elements of the vector
mytotal <- sum(myvector)
# divide each element by the sum
myvector / mytotal
## [1] 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
(myvector / mytotal) * 100
## [1]  5.555556 11.111111 16.666667  5.555556 11.111111 16.666667  5.555556 11.111111 16.666667