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
<- c(2, 3, 4, 5, 6, 7, 8, 9, 10, 11)
y # same as
<- 2:11
y # 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
2] y[
## [1] 3
5- Show the 3rd and the 6th elements of y.
Answer
c(3,6)] y[
## [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[-4]
y # 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:
< 7 y
## [1] TRUE TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE
# show those elements
< 7 ] y[ y
## [1] 2 3 4 6
8- Show all elements of y that are more than or equal to 4 and less than 9.
Answer
>= 4 & y < 9 ] y[ y
## [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:
<- c(1, 11, 5, 62, 18, 2, 8) y2
11- Which elements of y2 are also present in y ?
Note: remember the %in% operator.
Answer
%in% y ] y2[ y2
## [1] 11 2 8
9.2.2 Exercise 2b.
1- Create the vector myvector as:
<- c(1, 2, 3, 1, 2, 3, 1, 2, 3) myvector
2- Create the same vector using the rep.int() function (look for help: ?rep.int)
Answer
<- rep.int(x=1:3, times=3) myvector
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
<- sum(myvector)
mytotal # divide each element by the sum
/ mytotal myvector
## [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
/ mytotal) * 100 (myvector
## [1] 5.555556 11.111111 16.666667 5.555556 11.111111 16.666667 5.555556 11.111111 16.666667