1. Logical operators
While relational operators are great for simple comparisons, by themselves they aren't enough to do more complex comparisons. When you need to compare multiple conditions at once,
2. Logical operators
logical operators are there to help. There are three logical operators.
3. Logical operators
And, represented as an ampersand, is an intersection, meaning that it will only return TRUE if the conditions on either side of the ampersand are both true.
4. Logical operators
Or, represented as a vertical line, or pipe, is a union. This means that it will return TRUE if just one of the conditions are true, or both of them are true.
5. Logical operators
Not, as you've seen, is represented by an exclamation point, and this negates, or flips, the logical sign of a condition.
6. Logical operators
If you have a condition that returns TRUE, and you put a not in front of it, it will be flipped to a FALSE.
7. Logical operator examples
Logical operators make much more sense after a few examples. Let's look at some. The fictitious datacamp stock is currently at a price of 64-point-69. Suppose you want to know if this is in the range of 64 to 65. Obviously, it is, but how can you tell R to check this? In words, you want to check if datacamp is greater than 64, AND datacamp is less than 65. Translating that directly to code you can write the following. On the left side of the ampersand, the condition will evaluate to TRUE because datacamp stock is greater than 64. The right side will also evaluate to TRUE because datacamp is less than 65. Because both sides of the AND operator are true, the entire statement will evaluate to true. The two conditions don't have to be about the same object. If you wanted to know if datacamp is greater than 63 OR apple is greater than 126, you can write that like this. Datacamp is greater than 63 so the left side is true, but Apple stock is not above 126 so the right side is false. However, since you used OR, only 1 side has to evaluate to true, so this expression is true.
8. Logical operators + subset()
In the Introduction to R for Finance course, the subset function was introduced to select rows from a data frame that satisfied a specific condition. This can be combined with relational and logical operators to be even more flexible. The cash data frame was used in that course to represent the cash flows from two companies. To subset rows with low cash flow, you can use the condition, cash_flow less than 1000, inside of subset. To subset that even further to only include rows about company A, you can use the logical operator AND, to combine the previous condition with one that looks for rows only concerning company A.
9. Let's practice!