Selection by comparison - Step 1

By making use of comparison operators, we can approach the previous question in a more proactive way.

The (logical) comparison operators known to R are:

As seen in the previous chapter, stating 6 > 5 returns TRUE. The nice thing about R is that you can use these comparison operators also on vectors. For example:

> c(4, 5, 6) > 5
[1] FALSE FALSE TRUE

This command tests for every element of the vector if the condition stated by the comparison operator is TRUE or FALSE.

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 # Which days did you make money on poker? selection_vector <- # Print out selection_vector # 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 # Which days did you make money on poker? selection_vector <- poker_vector > 0 # Print out selection_vector selection_vector 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("selection_vector", incorrect_msg = "It looks like `selection_vector` does not contain the correct result. Remember that R uses element wise operations for vectors.") test_output_contains("selection_vector", incorrect_msg = "Don't forget to print out `selection_vector` by writing the variable name on a new line.") success_msg("Great!")

In order to check for which days your poker gains are positive, R should check for each element of poker_vector whether it is larger than zero. some_vector > 0 is the way to tell R what you are after.

Previous: 2-13 | Vector selection: the good times (4)

Next: 2-15 | Selection by comparison - Step 2

Back to Main