Steps to complete your assignment:

  1. Complete the tasks. Write your R code in the designated areas (you can send the code to the console to test your code).
  2. Create an HTML file in R-Studio: | Menu | File | Knit Document (alternatively: little Knit button in script header)
  3. RENAME the file: lastname_assignment01.html
  4. Upload your assignment (.html file) to Moodle

1. Create a vector from a series of numbers:

2;2;2;2;2;2;2;2;2;2;2;8;8;8;8;1;2;3;4;5;6;7;8;9;10;6;5;4;3;2;1;56;56;56;56;8;8;8;8;8

From the above number series construct a vector x using the functions c(), rep() and seq(). Note, you must use all three functions! Read the online script from the PCLab to answer the questions.

x <- c(
  rep(2, times = 11),
  rep(8, times = 4),
  seq(1:10),
  seq(6:1),
  rep(56, times = 4),
  rep(8, times = 5)
)
x
##  [1]  2  2  2  2  2  2  2  2  2  2  2  8  8  8  8  1  2  3  4  5  6  7  8  9 10
## [26]  1  2  3  4  5  6 56 56 56 56  8  8  8  8  8

2. How many elements has vector x?

length(x)
## [1] 40

3. Extract the 12th element from vector x.

x[12]
## [1] 8

4. Extract the elements 20-27 from vector x.

x[20:7]
##  [1] 5 4 3 2 1 8 8 8 8 2 2 2 2 2

5. Extract the 12th and 20-27th element from vector x.

x[c(12, 20:27)]
## [1]  8  5  6  7  8  9 10  1  2

6. Extract all but the 5th element from vector x and assign the new vector to a variable y. Print the content of y.

x[-5]->y
y
##  [1]  2  2  2  2  2  2  2  2  2  2  8  8  8  8  1  2  3  4  5  6  7  8  9 10  1
## [26]  2  3  4  5  6 56 56 56 56  8  8  8  8  8

7. Write a logical expression that assesses for each element i in vector x whether i is equal to 56. The result should be a logical vector of TRUEs and FALSEs that has the same number of elements as x.

x==56
##  [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [13] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [25] FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE FALSE
## [37] FALSE FALSE FALSE FALSE

8. Use the logical expression to replace all values 56 in vector x with the value 52. Print the content of x.

x[x==56]<- 52
x
##  [1]  2  2  2  2  2  2  2  2  2  2  2  8  8  8  8  1  2  3  4  5  6  7  8  9 10
## [26]  1  2  3  4  5  6 52 52 52 52  8  8  8  8  8

9. Replace all elements in vector x that are less than 5 or greater than 50 with the value NA. Use a logical expression, and print the result.

x[x < 5 | x > 50] <- NA
x
##  [1] NA NA NA NA NA NA NA NA NA NA NA  8  8  8  8 NA NA NA NA  5  6  7  8  9 10
## [26] NA NA NA NA  5  6 NA NA NA NA  8  8  8  8  8

10. Add 5 to each element in vector x.

x=x+5
x
##  [1] NA NA NA NA NA NA NA NA NA NA NA 13 13 13 13 NA NA NA NA 10 11 12 13 14 15
## [26] NA NA NA NA 10 11 NA NA NA NA 13 13 13 13 13