R – if statement

If statement is one of the Decision-making statements in the R programming language. It is one of the easiest decision-making statements.

It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.

Syntax:

if (expression) {
   #statement to execute if condition is true
}

If the expression is true, the statement gets executed. But if the expression is FALSE, nothing happens. The expression can be logical/numerical vector, but only the first element is taken into consideration.
In the case of numeric vector, zero is taken as FALSE, rest as TRUE.

If-statement-R



Working of if statement

  1. Control falls into the if block.
  2. The flow jumps to Condition.
  3. Condition is tested.
    1. If Condition yields true, goto Step 4.
    2. If Condition yields false, goto Step 5.
  4. The if-block or the body inside the if is executed.
  5. Flow steps out of the if block.

Flowchart:

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

# R program to illustrate if statement
  
# assigning value to variable a
a <- 5
   
# condition
if( a > 0 )
{
  print("Positive Number"# Statement
}

chevron_right


Output:

Positive Number

In this example, variable a is assigned a value of 2. The given expression will check if the value of variable a is greater than 0.
If the value of a is greater than zero, the print statement will be executed and the output will be “Positive Number”. If the value of a is less than 0, nothing will happen.

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Assigning value to variable x
x <- 12
  
# Condition
if (x > 20)
{
  print("12 is less than 20"# Statement
}
print("Hello World")

chevron_right


Output:

12 is less than 20
Hello World

In this example, variable x is assigned a value. The given expression will check if the value of variable x is greater than 20.
If the value of x is greater than 20, the statement given in the curly braces will be executed and the output will be “12 is less than 20”. Here, we have one more statement outside the curly braces. This statement will be executed whenever we run the program as it’s not a part of the given condition.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

2


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.