If … Else Conditional Statements

R supports the usual logical conditions from mathematics:

Operator Name Syntax Try it
== Equal x == y 5== (15/3) = TRUE

5== (4*3)= FALSE

!= Not equal x != y  5!=-5
> Greater than x > y 10> 8
< Less than x < y 7<10
>= Greater than or equal to x >= y 10>= 8 = TRUE

10>=10 = TRUE

<= Less than or equal to <= y

These conditions can be used in several ways, most commonly in “if statements” and loops. These opeators basically say if a statement is True or False.

The if Statement

  • An “if statement” is written with the if keyword, and it is used to specify a block of code to be executed if a condition is TRUE
  • In R, you place the code for the condition inside the parentheses of the if statement.
  • The code that has to be executed if the condition is TRUE follows in curly braces (expr).


a <- 10
b <- 15

if (b > 1){

print(“b is greater than a”)

}

[1] “b is greater than a”

Else If

  • The else if keyword is R’s way of saying “if the previous conditions were not true, then try this condition”:
  • There is no limit on the amount of else if statements that can be used
  • if the previous condition is not met, the code will keep running until the condition is met.
  • else can be used without the if

a <- 15
b <- 15

# check the relationship between both variables

if (a < b){

print(“a is less than b”)

} else if (a == b){

print (“a is equal to b”)

}

[1] “a is equal to b”

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top