Open In App

Nested if-else statement in R

Last Updated : 29 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss the nested if-else statement in the R programming language.

The if-else statements can be nested together to form a group of statements and evaluate expressions based on the conditions one by one, beginning from the outer condition to the inner one by one respectively. An if-else statement within another if-else statement better justifies the definition.

Syntax:

if(condition1){
# execute only if condition 1 satisfies
if(condition 2){ 
# execute if both condition 1 and 2 satisfy
}
}else{
}

Example: Nested if-else statement

R




# creating values
var1 <- 6
var2 <- 5
var3 <- -4
 
# checking if-else if ladder
if(var1 > 10 || var2 < 5){
  print("condition1")
}else{
  if(var1 <4 ){
    print("condition2")
  }else{
    if(var2>10){
      print("condition3")
    }
    else{
      print("condition4")
    }
  }
}


Output:

[1] "condition4"

Using ifelse statement

The first argument in the ifelse() method contains the condition to be evaluated. The second and third arguments contain the value on true and false evaluation of the condition respectively. In the case of evaluation with dataframe or other R objects, the columns are referred to type using the dataframe name. 

Syntax:

ifelse(cond, value-on-true, value-on-false)

Example: Nested if-else using ifelse

R




# creating a dataframe
data_frame <- data.frame(col1 = c(1:9),
                         col2 = LETTERS[1:3])
 
print("Original DataFrame")
print(data_frame)
 
data_frame$col3 = ifelse(data_frame$col1>4,"cond1 satisfied",
                         ifelse(data_frame$col2 %in% c("A","C"),
                                "cond2 satisfied",
                         "both failed"))
 
print("Modified DataFrame")
print(data_frame)


Output:

[1] "Original DataFrame" 
col1 col2 
1    1    A 
2    2    B 
3    3    C 
4    4    A 
5    5    B 
6    6    C 
7    7    A 
8    8    B 
9    9    C 
[1] "Modified DataFrame"
col1 col2            col3 
1    1    A cond2 satisfied 
2    2    B     both failed 
3    3    C cond2 satisfied 
4    4    A cond2 satisfied 
5    5    B cond1 satisfied 
6    6    C cond1 satisfied 
7    7    A cond1 satisfied 
8    8    B cond1 satisfied 
9    9    C cond1 satisfied

In the case of the nested dataframe, the nested conditions contain the dataframe name again and again. To save from this complexity and increase efficiency, the dataframe name is specified in the first argument of the with() method.

Syntax: 

with(data-frame , ifelse())

Example: Using with() with ifelse()

R




# creating a dataframe
data_frame <- data.frame(col1 = c(1:9),
                         col2 = LETTERS[1:3])
 
print("Original DataFrame")
print(data_frame)
 
data_frame$col3 = with(data_frame,
                       ifelse(col1>4,"cond1 satisfied",
                        ifelse(col2 %in% c("A","C"),
                               "cond2 satisfied",
                           "both failed")))
   
print("Modified DataFrame")
print(data_frame)


Output

[1] "Original DataFrame" 
col1 col2 
1    1    A 
2    2    B 
3    3    C 
4    4    A 
5    5    B 
6    6    C 
7    7    A 
8    8    B 
9    9    C 
[1] "Modified DataFrame"
col1 col2            col3 
1    1    A cond2 satisfied 
2    2    B     both failed 
3    3    C cond2 satisfied 
4    4    A cond2 satisfied 
5    5    B cond1 satisfied 
6    6    C cond1 satisfied 
7    7    A cond1 satisfied 
8    8    B cond1 satisfied 
9    9    C cond1 satisfied


Similar Reads

Decision Making in R Programming - if, if-else, if-else-if ladder, nested if-else, and switch
Decision making is about deciding the order of execution of statements based on certain conditions. In decision making programmer needs to provide some condition which is evaluated by the program, along with it there also provided some statements which are executed if the condition is true and optionally other statements if the condition is evaluat
5 min read
IF-ELSE-IF statement in R
if-else-if ladder in R Programming Language is used to perform decision making. This ladder is used to raise multiple conditions to evaluate the expressions and take an output based on it. This can be used to evaluate expressions based on single or multiple conditions connected by comparison or arithmetic operators. It is particularly useful to che
2 min read
R If Else Conditions
The if-statement in Programming Language alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if we want to do something else if the condition is false? Here comes the R Programming Language else statement. We can use the else statement with the if statement to execute a b
5 min read
R Next Statement
Next statement in R is used to skip any remaining statements in the loop and continue the execution of the program. In other words, it is a statement that skips the current iteration without loop termination. 'next' is a loop control statement just like the break statement. But 'next' statement works opposite to that of the break statement, instead
6 min read
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) { #s
3 min read
goto statement in R Programming
Goto statement in a general programming sense is a command that takes the code to the specified line or block of code provided to it. This is helpful when the need is to jump from one programming section to the other without the use of functions and without creating an abnormal shift. Unfortunately, R doesn't support goto but its algorithm can be e
2 min read
Case when statement in R Dplyr Package using case_when() Function
This article focuses upon the case when statement in the R programming language using the case_when() function from the Dplyr package. Case when is a mechanism using which we can vectorize a bunch of if and else if statements. In simple words, using a case when statement we evaluate a condition expression, and based on that we make decisions. For e
4 min read
Convert Nested Lists to Dataframe in R
In this article, we will discuss how to Convert Nested Lists to Dataframe in R Programming Language. It can be done with two methods: Convert Nested lists to Data Frame by Column.Convert Nested lists to Data Frame by Row. First, let's Create a nested list. Code block Output: Method 1: To convert nested list to Data Frame by column. Approach: Create
3 min read
How to Extract random sample of rows in R DataFrame with nested condition
In this article, we will learn how to extract random samples of rows in a DataFrame in R programming language with a nested condition. Method 1: Using sample() We will be using the sample() function to carry out this task. sample() function in R Language creates random samples based on the parameters provided in the function call. It takes either a
4 min read
Nested Pie Chart in R
In this article, we will discuss how to create a nested pie chart in the R Programming Language. A Pie Chart is a circular plot that can display only one series of data. The area of slices of the pie represents the ratio of the parts of the data that are visualized by that slice. But sometimes we need to show two series of data simultaneously to an
5 min read
Article Tags :