Vector selection: the good times (4)

Another way to tackle the previous exercise is by using the names of the vector elements (Monday, Tuesday, ...) instead of their numeric positions. For example,

poker_vector["Monday"]

will select the first element of poker_vector since "Monday" is the name of that first element.

Just like you did in the previous exercise with numerics, you can also use the element names to select multiple elements, for example:

poker_vector[c("Monday","Tuesday")]

Instruction

# Poker and roulette winnings from Monday to Friday: poker_vector <- c(140, -50, 20, -120, 240) roulette_vector <- c(-24, -50, 100, -350, 10) days_vector <- c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday") names(poker_vector) <- days_vector names(roulette_vector) <- days_vector # Select poker results for Monday, Tuesday and Wednesday poker_start <- # Calculate the average of the elements in poker_start # Poker and roulette winnings from Monday to Friday: poker_vector <- c(140, -50, 20, -120, 240) roulette_vector <- c(-24, -50, 100, -350, 10) days_vector <- c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday") names(poker_vector) <- days_vector names(roulette_vector) <- days_vector # Select poker results for Monday, Tuesday and Wednesday poker_start <- poker_vector[c("Monday", "Tuesday", "Wednesday")] # Calculate the average of the elements in poker_start mean(poker_start) msg = "Do not change anything about the definition and naming of `poker_vector` and `roulette_vector`." test_object("days_vector", undefined_msg = msg, incorrect_msg = msg) test_object("poker_vector", eq_condition = "equal", undefined_msg = msg, incorrect_msg = msg) test_object("roulette_vector", eq_condition = "equal", undefined_msg = msg, incorrect_msg = msg) test_object("poker_start", incorrect_msg = "It looks like `poker_start` does not contain the first three values of `poker_vector`. You can use `c(\"Monday\", \"Tuesday\", \"Wednesday\")` inside square brackets to do this.") test_output_contains("mean(poker_start)", incorrect_msg = "Have you correctly calculated the average of the values in `poker_start` and printed it out? Use `mean(poker_start)`.") success_msg("Good job! Apart from subsetting vectors by index or by name, you can also subset vectors by comparison. The next exercises will show you how!");
  • You can use c("Monday", "Tuesday", "Wednesday") inside square brackets to subset poker_vector appropriately.
  • You can use mean(poker_start) to get the mean of the elements in poker_start. You do not need the mean of all poker elements, but only of the first three days.

Previous: 2-12 | Vector selection: the good times (3)

Next: 2-14 | Selection by comparison - Step 1

Back to Main