Task 1

Specify a vector with numeric elements 1 and 3 and a character element “c”.

What type will the resulting object be?

Check your intuition with R.

Task 2

Create a named list containing a data frame, a character vector, and a list. Access the first element of the first element and the second element.

Task 3

Assign the name “x” to an integer vector from 1 to 10.

Create a logical vector “z” whose elements store whether x is greater than 2 and less than 8.

Compute the number of times the above condition is true (use sum()).

Task 4

Given the data frame below, create a new column called “c” that contains the product of “a” and “b”. Do this using $ and [ indexing (and maybe names()). Remember, data frames are (special) lists!

df <- data.frame(
  a = c(1,1,2,3,4),
  b = c(3,2,2,4,5)
)

Your solution:

Task 5

In this task, you will learn a few essential functions in base R.

1. Sequences

Often, you want to create sequences of objects.

You can do so using the rep() function:

x <- c(1,2,3)
rep(x, 3)
## [1] 1 2 3 1 2 3 1 2 3
rep(x, each = 3)
## [1] 1 1 1 2 2 2 3 3 3

Another way of creating sequences is seq():

seq(1, 5)
## [1] 1 2 3 4 5
1:5
## [1] 1 2 3 4 5
seq(1,5, by = 2)
## [1] 1 3 5

2. Manipulating Strings

You should also know some basic string manipulations from the beginning.

With paste() you can concatenate strings:

x <- "a"

paste(x, 3)
## [1] "a 3"
paste(3, x)
## [1] "3 a"
paste(3, x, sep = "")
## [1] "3a"

Can you spot the difference to paste0()?

paste0(3, x)
## [1] "3a"

3. Classic (math) functions

Some very basic (math) functions: sqrt(), exp(), log(), abs(), sum(), max(), min(), length() (length of an r object).

TASK:

Create a character vector with 20 elements: “1st element”, “2nd element”, “3rd element”, “4th element”, etc.

Task 6

Write a function to compute the mean of a vector. Of course, without using the mean() function.

Define a vector you want to test your function on and specify the expected result:

Write the function and test it: