10 Feb 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:
1 2 3 4 5 |
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:
1 2 3 4 5 6 7 8 |
age <- 20 # The if statement if (age > 18) { print("You can Vote!") } |
Output
1 2 3 |
[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:
1 2 3 4 5 6 7 8 |
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:
1 2 3 4 5 6 7 8 9 10 |
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 2 3 |
[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:
1 2 3 4 5 6 7 8 9 10 11 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 |
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 2 3 |
[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:
No Comments