7.4 Combining logical operators
The functions that we’ve created so far have been perfectly suited for what we need, though they have been fairly simplistic. Let’s try creating a function that has a little more complexity to it. We’ll make a function to determine if today is going to be a good day or not based on two criteria. The first criteria will depend on the day of the week (Friday or not) and the second will be whether or not your code is working (TRUE or FALSE). To accomplish this, we’ll be using if
and else
statements. The complexity will come from if
statements immediately following the relevant else
statement. We’ll use such conditional statements four times to achieve all combinations of it being a Friday or not, and if your code is working or not.
good.day <- function(code.working, day) {
if (code.working == TRUE && day == "Friday") {
"BEST. DAY. EVER. Stop while you are ahead and go to the pub!"
} else if (code.working == FALSE && day == "Friday") {
"Oh well, but at least it's Friday! Pub time!"
} else if (code.working == TRUE && day != "Friday") {
"So close to a good day... shame it's not a Friday"
} else if (code.working == FALSE && day != "Friday") {
"Hello darkness."
}
}
good.day(code.working = TRUE, day = "Friday")
## [1] "BEST. DAY. EVER. Stop while you are ahead and go to the pub!"
good.day(FALSE, "Tuesday")
## [1] "Hello darkness."
Notice that we never specified what to do if the day was not a Friday? That’s because, for this function, the only thing that matters is whether or not it’s Friday.
We’ve also been using logical operators whenever we’ve used if
statements. Logical operators are the final piece of the logical conditions jigsaw. Below is a table which summarises operators. The first two are logical operators and the final six are relational operators. You can use any of these when you make your own functions (or loops).
Operator | Technical Description | What it means | Example |
---|---|---|---|
&& |
Logical AND | Both conditions must be met | if(cond1 == test && cond2 == test) |
|| |
Logical OR | Either condition must be met | if(cond1 == test || cond2 == test) |
< |
Less than | X is less than Y | if(X < Y) |
> |
Greater than | X is greater than Y | if(X > Y) |
<= |
Less than or equal to | X is less/equal to Y | if(X <= Y) |
>= |
Greater than or equal to | X is greater/equal to Y | if(X >= Y) |
== |
Equal to | X is equal to Y | if(X == Y) |
!= |
Not equal to | X is not equal to Y | if(X != Y) |