R – Decision Making Statements

With R decision-making statements you can easily take decisions based on different conditions. The following are the decision-making statements in the R programming language:

  • if statement
  • if…else statement
  • if…elseif..else statement

if statement

The if decision-making statement executes the code if the condition is true. The following is the syntax:

if (condition is true) {
   // statement(s) will execute if the condition is true
}

Let us see an example to implement the if statement in the R programming language:

age <- 20

# The if statement
if (age > 18) {
  print("You can Vote!")
}

Output

[1] "You can Vote!"

if…else statement

The if…else decision-making statement executes some code if the condition is true and another code if the condition is false. The false condition comes under else.

The following is the syntax:

if (condition is true) {
  // code will execute if the condition is true
}
else {
   // code will execute if the condition is false
}

Let us see an example to implement the if…else statement in the R programming language:

age <- 15

# The if...else statement
if (age > 18) {
  print("You can Vote!")
} else {
  print("Your age is less than 18, therefore you cannot vote.")
}

Output

[1] "Your age is less than 18, therefore you cannot vote."

if…else if…else statement

The if…else if…else statement executes code for different conditions. If more than 2 conditions are true, you can use else for the false condition.

The following is the syntax:

if (condition1 is true) {
   // code will execute if the condition is true
} else if (condition2 is true) {
   // code will execute if condition2 is true
} else if (condition3 is true) {
   // code will execute if condition3 true
} else {
   // code will execute if all the above given conditions are false
}

Let us see an example to implement the if…else if…else statement in the R programming language:

age <- 18

# The if...elseif...else statement
if (age > 18) {
  print("You can Vote!")
} else if (age == 18) {
  print("Your age is 18, therefore you can vote.")
} else {
   print("Your age is less than 18, therefore you cannot vote.")
}

Output

[1] "Your age is 18, therefore you can vote."

If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.


Read More:

R Loop Control Statements
R Strings
Studyopedia Editorial Staff
contact@studyopedia.com

We work to create programming tutorials for all.

No Comments

Post A Comment