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

correction

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 11

3- How many elements are in y? I.e what is the length of vector y ?

correction

## [1] 10

4- Show the 2nd element of y.

correction

## [1] 3

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

correction

## [1] 4 7

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

correction

## [1] 9

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 6

8- Show all elements of y that are superior or equal to 4 and inferior to 9.

correction

## [1] 4 6 7 8

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

11- 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.07949

12- Create vector y2 as:

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

correction

## [1] 11  2  8

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] TRUE

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

## [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

##  [1]  1  2  3  1  8 12 32  2  3  2  4  6  7