Working with conditionals means that we will be using logical, true or false values. In R, there are operators that work with logical values known as logical operators. We can use logical operators to add more sophisticated logic to our conditionals. There are three logical operators:
- the AND operator (
&
) - the OR operator (
|
) - the NOT operator, otherwise known as the bang operator (
!
)
When we use the &
operator, we are checking that two things are true:
if (stopLight == 'green' & pedestrians == 0) { print('Go!'); } else { print('Stop'); }
When using the &
operator, both conditions must evaluate to true for the entire condition to evaluate to true and execute. Otherwise, if either condition is false, the &
condition will evaluate to false and the else block will execute.
If we only care about either condition being true, we can use the |
operator:
if (day == 'Saturday' | day == 'Sunday') { print('Enjoy the weekend!') } else { print('Do some work.') }
When using the |
operator, only one of the conditions must evaluate to true for the overall statement to evaluate to true. In the code example above, if either day == 'Saturday'
or day == 'Sunday'
evaluates to true the if’s condition will evaluate to true and its code block will execute. If the first condition in an |
statement evaluates to true, the second condition won’t even be checked.
The !
NOT operator reverses, or negates, the value of a TRUE value:
excited <- TRUE print(!excited) # Prints FALSE
Essentially, the !
operator will either take a true value and pass back false, or it will take a false value and pass back true.
Logical operators are often used in conditional statements to add another layer of logic to our code.
Instructions
There are two variables in your code, weather
and high_chance_of_rain
. Write a conditional statement that:
- Checks to see if
weather
is equalcloudy
and there is ahigh_chance_of_rain
. - If it is both, the code block should assign the value of the variable
message
to be"Pack umbrella!"
- Otherwise, the code block should assign the value of the variable
message
to"No need for umbrella!"
- Print the
message
variable after the conditional statement. Based on the condition, what should its value be?