Logical Operators & If Else Statements - R Basics

In this post, we talk about AND, OR, NOT and If Else Statements. The basic fundamentals of programming.

·

7 min read

Hello everyone and welcome to another chapter of R Basics. Today is going to be an exciting day because we are finally going to start learning the basics of programming, not just in R but in general, this knowledge can be brought forward to other programming languages as well with some minor changes in the syntax. What's important is the logic and concept behind it. Now without further ado, let's get started with...

Logical Operators

In this section, we will be combining logical operators with comparison operators which you are learn about here. But through this post, you'll probably also be able to learn about comparison operators if you already know basic maths.

The logical operators allow us to combine multiple comparison operators and there are mainly 3:

  • AND - &
  • OR - | (Shift + Backslash)
  • NOT - !

Let's see some examples to get a better understanding. First let's assign the number 20 to the variable x.

x <- 20

AND (&)

To use the AND operators, just put a '&' symbol between 2 arguments.

#Is x bigger than 5 AND smaller than 50?
x > 5 & x < 50
[1] TRUE

You can also add parenthesis / brackets '( )' for better readability of your code.

(x < 35) & (x == 20) & (x>=15)
[1] TRUE

(x > 50) & (x == 20) & (x < 100)
[1] FALSE

Because AND requires all arguments to be TRUE, if even one of the arguments is FALSE, the resulting Boolean Value is FALSE. In the examples above:

TRUE TRUE TRUE -> TRUE

FALSE TRUE TRUE -> FALSE

OR (|)

OR works in the same way as AND where you put them in between arguments. The only difference is that when using OR, only one of the arguments has to be TRUE for the resulting Boolean Value to be TRUE.

x > 5 | x < 10
[1] TRUE

x == 20 | x == 15
[1] TRUE

NOT (!)

NOT is just basically reversing any logical values in front of it. Make sure to pay attention to your parenthesis

#Is x NOT bigger than 50?
!x > 50
[1] TRUE

#Is x NOT bigger than 50 AND equal to 20?
!x > 50 & x == 20
[1] TRUE

#Is x NOT (bigger than 50 AND equal to 20)?
!(x > 50 & x == 20)
[1] TRUE

#Is x (NOT bigger than 50) AND (NOT equal to 20)?
!(x > 50) & !(x == 20)
[1] FALSE

If, Else, Else If, If Else statements

Another super useful tool to add to our arsenal are the if else statements. There are several types but I will be covering the 4 main types as these should be sufficient for any problems that we may need it for unless you are looking for something very specific.

A lot of times in programming, we will talk about if else statements. Why is that? It's because that's how most basic computers operate. If else statements allow computers to cater for different scenarios, run different procedures and provide a different output depending on the input(s) it receives.

If Statement

The basic syntax for an if statement in R is as follows:

if (condition){
  #Execute this code
}

If you aren't sure what you are reading right now, let's think logically and take it step-by-step. IF the CONDITION in the brackets () is met, execute the code in the curly brackets {}. It's just that simple. If you still don't understand the code, try to read it one section at a time, that should help.

When writing if else statements, please focus on the formatting of your code, it will greatly improve the readability so that you and the people you are collaborating with won't be confused when you or they come back and read it. If else statements can get complicated fast. In theory, you could write it in a single line if you wanted to, but I highly recommend you DON'T do that.

Let's look at an example about the temperature of water and whether it is considered hot. For this exercise, let's say we have 2 variables (temp & hot). If the temperature of the water greater than or equal to 50 degrees Celsius, then it is HOT. Let's transform this sentence into R language. First, we need to create the 2 variables and set it's default value.

temp <- 0
hot <- FALSE

Let's say our temp is at 68 degrees.

temp <- 68

if (temp >= 50){
  hot <- TRUE
}

> hot
[1] TRUE

Let's say our temp now is at 32 degrees.

temp <- 32

if (temp >= 50){
  hot <- TRUE
}

> hot
[1] FALSE

Else

An IF statement can only handle 1 condition, but if we have 2 conditions, we can add an ELSE statement for the scenarios where the condition is NOT met. The syntax for an IF ELSE statement is as follows:

if (condition){
  #Execute this code
}else{
  #Execute this code instead
}

Let's use back our water temperature scenario and say that: If the temp is higher than or equal to 50 degrees, then hot = TRUE, else hot = FALSE.

if (temp >= 50){
  hot <- TRUE
}else{
  hot <- FALSE
}

Test around with different values assigned to the temp variable and see what's the result.

Else If

We learnt how to handle cases where there are one or two possible scenarios with different outputs, but how many 3 or 4 or 5? This is where ELSE IF comes in. Else if is placed in between the beginning If and ending else statements to cater for more scenarios. The syntax for an ELSE IF statement is as follows:

if (condition){
  #Execute this code
}else if (condition){
  #Execute this code instead
}else{
  #Execute this code if neither conditions are met
}

I think you should be getting the hang of it by now. If you have another condition to add on, just add another else if statement. You can do it as many times as you like, but of course, don't overuse it too often as it may clutter up your code until it's unreadable. But just in case, let's do an example with water and print out a few statements based on its temperature.

temp <- *place any number here*

if (temp <= 0){
  print("The water is frozen.")
}else if (temp >= 100){
  print("The water is boiling.")
}else if (temp > 0 & temp <= 20){
  print("The water is cold.")
}else if (temp >= 40 & temp < 100){
  print("The water is hot.")
}else{
  print("The water is drinkable")
}

In this example, I have put in 5 different scenarios which will output a different statement depending on the value of the temp variable. Feel free to experiment and create your own example.

If Else

This is actually one of my favorite if statements because it's short and simple to read. The If Else statement can only be used with 2 scenarios (similar to if and else), however, the if else statement is generally written in a single line and if the outputs are short. The syntax for this statement is as follows:

ifelse(condition, output if true, output if false)

Comparing this to the if & else statement, it turns from 5 lines to 1 single line. Let's use back the same example of whether the hot variable is TRUE or FALSE based on the temperature.

#We can rewrite this code
if (temp >= 50){
  hot <- TRUE
}else{
  hot <- FALSE
}

#Into this code
ifelse(temp >= 50,TRUE,FALSE)

Looks so much neater and it works in exactly the same way and this brings us to the end of this section and this post as well. Please take your time to go through these concepts and understand the syntax, logic and concept of what we learnt today. You will probably use it very often in your programming future.

That's all for this post and thank you so much for joining me on my coding and data science journey. In my next post, I will be talking about another concept called loops and functions (if I can squeeze it into a single post without it being too long). See you guys next time!