ListenData

If Else Conditions in R (with Examples)

This tutorial explains various ways to apply IF ELSE conditional statements in R, along with examples.

There are the following two ways to handle conditional statements in R.

  • ifelse() function
  • if-else statement

Below is the syntax of the ifelse() function in R. It works similar to MS Excel IF function.

ifelse(condition, value if condition is true, value if condition is false)

Below is the syntax of the if-else statement in R.

ifelse() Function

In this section, we will cover ifelse() Function in detail.

Examples : ifelse Function

Below are examples showing the application of the ifelse() function in R.

x1 x2 x3
1 129 A
3 178 B
5 140 C
7 186 D
9 191 E
11 104 F
13 150 G
15 183 H
17 151 I
19 142 J

Run the syntax below to generate the above table in R.

Suppose you are asked to create a binary variable - 1 or 0 based on the variable 'x2'. If value of a variable 'x2' is greater than 150, assign 1 else 0.

In this case, it creates a variable x4 on the same data frame 'mydata'. The output is shown in the image below -

ifelse : Output
mydata$y = ifelse(mydata$x3 %in% c("A","D") ,mydata$x1*2,mydata$x1*3)

Multiple ifelse functions can be written similarly to excel's If function. In this case, we are telling R to multiply variable x1 by 2 if variable x3 contains values 'A' 'B'. If values are 'C' 'D', multiply it by 3. Else multiply it by 4.

You can use with() function to avoid mentioning data frame each time. It makes writing R code faster.

Let's dive into the important points regarding the ifelse function, which is commonly used to solve real-world data problems.

How to treat missing values in ifelse Function?

In R, missing values are denoted by the special value NA (Not Available).

How to use OR and AND operators in ifelse Function

ifelse(mydata$x1<10 & mydata$x2>150,1,0)
ifelse(mydata$x1<10 | mydata$x2>150,1,0)

How to combine summary and ifelse functions?

sum(ifelse(mydata$x1<10 | mydata$x2>150,1,0))

If Else Statement

There is one more way to define conditional statement in R i.e. if-else statement . This style of writing If-Else is mostly used when we use conditional statements in loop and R functions. In other words, it is used when we need to perform various actions based on a condition.

Examples : If..Else If..Else Statements

The code below would return the value 0 because the condition k > 100 is false.

The following code sets a variable k to 100. It checks if k is greater than 100. Since it's not, it checks if k is less than 100 which is also false. So it prints "Equal to 100".

ifelse function vs If-Else Statement

Below are the main differences between the ifelse function and the if-else statement in R.

  • Usage: ifelse() function is commonly used when applying a condition to an entire vector or column of data. whereas, if-else statement is typically used when dealing with more complex conditional logic.
  • Vectorized vs Scalar: The ifelse() function can work with entire vectors or columns of data at once, while the if-else statement operates on individual values.
  • Output Length: The ifelse() function returns a vector with the same length as the input. On the other hand, the if-else statement returns a single value or executes blocks of code.

If Else in Popular R Packages

Other than base R, there are functions available in packages for If Else conditions.

dplyr: If Else

Below is the syntax of if_else( ) function of dplyr package in R.

if_else(condition, value if condition is true, value if condition is false, value if NA)

Example 1: Using if_else() to create a new column.

The following program creates a new column called "SpeciesType" based on the condition that if the "Species" column is equal to "setosa", the corresponding "SpeciesType" value is set to "Type A". Otherwise it's set to "Type B".

Example 2: Checks whether a value is a multiple of 2

sqldf: If Else

We can write SQL query in R using sqldf package. In SQL, If Else statement is defined in CASE WHEN statement.

Below is a list of operators frequently used in if-else conditions in R.

  • == : Equal to
  • != : Not equal to
  • < : Less than
  • > : Greater than
  • <= : Less than or equal to
  • >= : Greater than or equal to
  • & : Logical AND
  • | : Logical OR
  • ! : Logical NOT
  • Compound Operator : %in% : Multiple OR conditions. Checks if a value is in a vector or set

Deepanshu Bhalla

Deepanshu founded ListenData with a simple objective - Make analytics easy to understand and follow. He has over 10 years of experience in data science. During his tenure, he worked with global clients in various domains like Banking, Insurance, Private Equity, Telecom and HR.

if else in r multiple assignments

how to apply this ( use ifelse with more than one condition0. i want to highlight any brand contain "lifestyle". this code gave me error library(dplyr) # for data manipulation library(tidyr) df <- df %>% mutate(Make = row.names(df), ID = ifelse(names.effectifs %in% c("Lifestyle","Diet Lifestyle","Lifestyle Plus", TRUE, FALSE), ggplot(df, aes(reorder(names.effectifs, -effectifs),effectifs, fill = ID)) + geom_bar(stat = "identity") + coord_flip() + scale_fill_manual(values = c("grey90", "dodgerblue")) + annotate("text", x = "Lifestyle", y =-8, label = "Eff=-10", color = "white") + theme_minimal() + theme(legend.position = "none")+ ggtitle(" DECREASED | INCREASED")

Hello, great examples thank you. Could you please make an example from this Excel formula? =IF(AT57=1;1;IF(B57=$C$50;1;B57+1)) Thanx

great learning

HI , I have three location denoted as 1,2,3 in the data set , i wanted to change the location name 1,2,3 to A, B and 3 respectively . How can i change that in r?

  • Subscription

How to Use If-Else Statements and Loops in R

When we're programming in R (or any other language, for that matter), we often want to control when and how particular parts of our code are executed. We can do that using control structures like if-else statements, for loops, and while loops.

Control structures are blocks of code that determine how other sections of code are executed based on specified parameters. You can think of these as a bit like the instructions a parent might give a child before leaving the house:

" If I'm not home by 8pm, make yourself dinner."

Control structures set a condition and tell R what to do when that condition is met or not met. And unlike some kids, R will always do what we tell it to! You can learn more about control structures in the R documentation if you would like.

In this tutorial, we assume you’re familiar with basic data structures, and arithmetic operations in R.

Not quite there yet? Check out our Introductory R Programming course that's part of our Data Analyst in R path. It’s free to start learning, there are no prerequisites, and there's nothing to install — you can start learning in your browser right now.

(This tutorial is based on our intermediate R programming course , so check that out as well! It's interactive and will allow you to write and run code right in your browser.)

Comparison Operators in R

In order to use control structures, we need to create statements that will turn out to be either TRUE or FALSE . In the kids example above, the statement "It's 8pm. Are my parents home yet?" yields TRUE ("Yes") or FALSE ("No"). In R, the most fundamental way to evaluate something as TRUE or FALSE is through comparison operators .

Below are six essential comparison operators for working with control structures in R:

  • == means equality. The statement x == a framed as a question means "Does the value of x equal the value of a ?"
  • != means "not equal". The statement x == b means "Does the value of x not equal the value of b ?"
  • < means "less than". The statement x < c means "Is the value of x less than the value of c ?"
  • <= means "less than or equal". The statement x <= d means "Is the value of x less or equal to the value of d ?"
  • > means "greater than". The statement x > e means "Is the value of x greater than the value of e ?"
  • >= means "greater than or equal". The statement x >= f means "Is the value of x greater than or equal to the value of f ?"

Understanding If-Else in R

Let's say we're watching a sports match that decides which team makes the playoffs. We could visualize the possible outcomes using this tree chart:

if-else-r-programming

As we can see in the tree chart, there are only two possible outcomes. If Team A wins, they go to the playoffs. If Team B wins, then they go.

Let's start by trying to represent this scenario in R. We can use an if statement to write a program that prints out the winning team.

If statements tell R to run a line of code if a condition returns TRUE . An if statement is a good choice here because it allows us to control which statement is printed depending on which outcome occurs.

The figure below shows a conditional flow chart and the basic syntax for an if statement:

if-else-r-2

Our if statement's condition should be an expression that evaluates to TRUE or FALSE . If the expression returns TRUE, then the program will execute all code between the brackets { } . If FALSE, then no code will be executed.

Knowing this, let's look at an example of an if statement that prints the name of the team that won.

It worked! Because Team A had more goals than Team B, our conditional statement( team_A > team_B ) evaluates to TRUE , so the code block below it runs, printing the news that Team A won the match.

Adding the else Statement in R

In the previous exercise, we printed the name of the team that will make the playoffs based on our expression. Let's look at a new matchup of scores. What if Team A had 1 goal and Team B had 3 goals. Our team_A > team_B conditional would evaluate to FALSE . As a result, if we ran our code, nothing would be printed. Because the if statement evaluates to false, the code block inside the if statement is not executed:

If we return to our original flow chart, we can see that we've only coded a branch for one of the two possibilities:

team_a-1

Ideally, we'd like to make our program account for both possibilities and "Team B will make the playoffs" if the expression evaluates to FALSE. In other words, we want to be able to handle both conditional branches:

team_a_b-1

To do this, we'll add an else statement to turn this into what's often called an if-else statement . In R, an if-else statement tells the program to run one block of code if the conditional statement is TRUE , and a different block of code if it is FALSE . Here's a visual representation of how this works, both in flowchart form and in terms of the R syntax:

if-else-r-2

To generalize, if-else in R needs three arguments:

  • A statement (e.g. comparison operator) that evaluates to TRUE or FALSE.
  • The value that R should return if the comparison operator is TRUE.
  • The value that R should return if the comparison operator is FALSE.

So for our example we need to add a block of code that runs if our conditional expression team_A > team_B returns FALSE . We can do this by adding an else statement in R. If our comparison operator evaluates to FALSE, let's print "Team B will make the playoffs."

  • The essential characteristic of the if statement is that it helps us create a branching path in our code.
  • Both the if and the else keywords in R are followed by curly brackets { } , which define code blocks.
  • Each of the code blocks represent one of the paths shown in the diagram.
  • R does not run both, and it uses the comparison operator to decide which code block to run.

Moving Beyond Two Branches

So far, we've worked under the assumption that each of the decisions in our control structure had only two branches: one corresponding to TRUE and another to FALSE . There are plenty of occasions where we have more than two since some decisions don't boil down to a "Yes" vs "No".

Suppose, for a moment, that we are watching a sports match that can end in a tie. The control structure from our last example does not account for this. Fortunately, R provides a way to incorporate more than two branches in an if statement with the else if keyword. The else if keyword provides another code block to use in an if statement, and we can have as many as we see fit. Here's how this would look:

Each potential game outcome gets its own branch. The else code block helps cover us for any situation where there is a tie.

Using the for loop in R

Now that we've used if-else in R to display the results of one match, what if we wanted to find the results of multiple matches? Let's say we have a list of vectors containing the results of our match: matches <- list(c(2,1),c(5,2),c(6,3)) .

Keep in mind that we'll have to use [[]] when indexing, since we want to return a single value within each list on our list, not the value with the list object. Indexing with [] will return a list object , not the value.

So, for example, in the code we have above, matches[[2]][1] is calling the first index of the second list (i.e., Team A's score in Game 2).

Assuming that Team A's goals are listed first (the first index of the vector) and Team B's are second, we could find the results using if-else in R like this:

And this would print:

This code works, but if we look at this approach it's easy to see a problem. Writing this out for three games is already cumbersome. What if we had a list of 100 or 1000 games to evaluate?

We can improve on our code by performing the same action using a for loop in R. A for loop repeats a chunk of code multiple times for each element within an object. This allows us to write less code (which means less possibility for mistakes) and it can express our intent better. Here's a flow chart representation, and the syntax in R (which looks very similar to the if syntax).

forloop_v2-1

In this diagram, for each value in the sequence, the loop will execute the code block. When there are no more values left in the sequence, this will return FALSE and exit the loop.

Let's break down what's going on here.

  • sequence : This is a set of objects. For example, this could be a vector of numbers c(1,2,3,4,5).
  • value : This is an iterator variable you use to refer to each value in the sequence. See variables naming conventions in the first course for valid variable names.
  • code block : This is the expression that's evaluated.

Let's look at a concrete example. We'll write a quick loop that prints the value of items in a list, and we'll create a short list with two items: Team A and Team B.

Since teams has two values, our loop will run twice. Here's a visual representation of what's going on

forloop_v6-1

Once the loop displays the result from the first iteration, the loop will look at the next value in the position. As a result, it'll go through another iteration. Since there aren't any more values in the sequence, the loop will exit after "team_B".

In aggregate, the final result will look like this:

Adding the Results of a Loop to an Object in R

Now that we've written out our loop, we'll want to store each result of each iteration in our loop. In this post, we'll store our values in a vector, since we're dealing with a single data type.

As you may already know from our R Fundamentals course , we can combine vectors using the c() function. We'll use the same method to store the results of our for loop.

We'll start with this for loop:

Now, let's say we wanted to get the total goals scored in a game and store them in the vector. The first step we'd need to do would be to add each score from our list of lists together, which we can do using the sum() function. We'll have our code loop through matches to calculate the sum of the goals in each match.

But we still haven't actually saved those goal totals anywhere! If we want to save the total goals for each match, we can initialize a new vector and then append each additional calculation onto that vector, like so:

Using if-else Statements Within for loops in R

Now that we've learned about if-else in R, and for loops in R, we can take things to the next level and use if-else statements within our for loops to give us the results of multiple matches.

To combine two control structures, we'll place one control structure in between the brackets { } of another.

We'll start with these match results for team_A:

Then we'll create a for loop to loop through it:

This time, rather than print our results, let's add an if-else statement into the for loop.

In our scenario, we want our program to print whether Team A won or lost the game. Assuming Team A's goals is the first of each pair of values and the opponents is the second index, we'll need to use a comparison operator to compare the values. After we make this comparison, if team_A's score is higher, we'll print "Win". If not, we'll print "Lose".

When indexing into the iterable variable match, we can use either [] or [[]] since the iterable is a vector, not a list.

Breaking the for loop in R

Now that we've added an if-else statement, let's look at how to stop a for loop in R based on a certain condition. In our case, we can use a break statement to stop the loop as soon as we see Team A has won a game.

Using the for loop we wrote above, we can insert the break statement inside our if-else statement.

Using a while loop in R

In the previous exercise, we used a for loop in R to repeat a chunk of code that gave us the result of the match. Now that we've returned the results of each match, what if we wanted to count the number of wins to determine if they make the playoffs? One method of returning the results for the first four games is to use a while loop in R.

A while loop in R is a close cousin of the for loop in R. However, a while loop will check a logical condition, and keep running the loop as long as the condition is true. Here's what the syntax of a while loop looks like:

In flow-chart form:

while_v2-1

If the condition in the while loop in R is always true, the while loop will be an infinite loop, and our program will never stop running. This is something we definitely want to avoid! When writing a while loop in R, we want to ensure that at some point the condition will be false so the loop can stop running.

Let's take a team that's starting the season with zero wins. They'll need to win 10 matches to make the playoffs. We can write a while loop to tell us whether the team makes the playoffs:

Our loop will stop running when wins hits 10. Notice, that we continuously add 1 to the win total, so eventually, the win < 10 condition will return FALSE . As a result, the loop exits.

Don't worry if this whole process seems daunting, while loops in R take time to understand, but they are powerful tools once mastered. There are a lot of different variables to juggle, but the key to understanding the while loop is to know how these variables change every time the loop runs.

Let's write our first while loop in R, counting Team A wins!

Using an if-else Statement within a while loop in R

Now that we've printed the status of the team when they don't have enough wins, we'll add a feature that indicates when they do make the playoffs.

To do this, we'll need to add an if-else statement into our while loop. Adding an if-else statement into a while loop is the same as adding it to a for loop in R, which we've already done. Returning to our scenario where 10 wins allows Team A to make the playoffs, let's add an if-else conditional.

The if-else conditional will go between the brackets of the while loop, in the same place we put it into the for loop earlier.

Breaking the while loop in R

Let's say the maximum number of wins a team can have in a season is 15. To make the playoffs, we'll still need 10 wins, so we can end our loop as soon as Team A has hit this number.

To do this, we can use another break statement. Again, this functions the same way in a while loop that it does in a for loop; once the condition is met and break is executed, the loop ends.

Intuition Behind the while loop

The for loop in R is the loop that you'll probably deal with the most often. But the while loop is still useful to know about.

To distinguish between these two types of loops, it's useful to think of a for loop as dealing with a chore list. The idea is that you have a set amount of chores to finish, and once you do all of your chores, you're done. The key here is that there is a set amount of items that we need to loop through in a for loop.

On the other hand, a while loop is like trying to reach a milestone, like raising a target amount of money for a charity event. For charity events, you typically perform and do things to raise money for your cause, like running laps or giving services to people. You do these tasks until you reach your target goal, and it's not clear from the beginning how many tasks you need to do to reach the goal. That's the key idea behind a while loop: repeat some actions (read: a code chunk) until a condition or goal is met .

Loop Comparison

While loops play a major role in heavy analytical tasks like simulation and optimization. Optimization is the act of looking for a set of parameters that either maximize or minimize some goal.

In other data analysis tasks, like cleaning data or calculating statistics, while loops are not so useful. These tasks form the brunt of what you encounter in the Data Analyst in R path and perhaps your career, but it's always good to know what tools are available to you as a programmer.

In this tutorial, we've developed a basic if statement into a more complex program that executes blocks of code based on logical conditions.

These concepts are important aspects of R programming, and they will help you write significantly more powerful code. But we're barely scratching the surface of R's power!

To learn to write more efficient R code, check out our R Intermediate course. You can write code (and get it checked) right in your browser!

In this course, you'll learn:

  • How and why you should use vectorized functions and functionals
  • How to write your own functions
  • How tidyverse packages dplyr and purrr can help you write more efficient and more legible code
  • How to use the stringr package to manipulate strings

In short, these are the foundational skills that will help you level up your R code from functional to beautiful. Ready to get started?

More learning resources

R api tutorial: getting started with apis in r, tutorial: poisson regression in r.

Learn data skills 10x faster

Headshot

Join 1M+ learners

Enroll for free

  • Data Analyst (Python)
  • Gen AI (Python)
  • Business Analyst (Power BI)
  • Business Analyst (Tableau)
  • Machine Learning
  • Data Analyst (R)

                    --->

R if...else Statement

Learn how to write if statement and if...else statement in R programming with Examples and Flowchart.

Conditional statements form the building blocks of any programming language for decision making. In R programming a conditional statement consists of atleast one test condition which is a boolean expression that evaluates in to either True or False which forms the basis of execution or non execution of certain code. This is done in R using if & if...else statement. 

R if statement

if statement is used when there is only one test condition and on the basis of that you have to take a decision. First the condition is checked. If the boolean expression results in to True the body of if statement is executed, otherwise R code in the specific block is skipped. 

The syntax of if statement is

if (test condition) {

    body of if

Now in case test condition is True, body of if is executed. When test condition is false the code in the body is ignored.

Flowchart of if statement

You can see the idea here in flowchart.

Example: if statement

score <- 70

if (score > 50){

    print('PASS')

When you write the code in rstudio it will be like 

and the output on rstudio is 

As the score is 75, hence the condition will result in a True and it will execute the code in the body of if statement i.e. it will print "PASS" on console.

if...else statement

The basic syntax for creating an if...else statement is 

if (condition) {

    //code to be executed if condition is True

    //code to be executed if condition is False

Flowchart of if else statement:

Flowchart of if...else statement in R programming

Example of if...else statement:

Here we are adding else code in the previous example. 

score <- 45

if ( score > 50){

print("PASS")

}  else  {

print("FAIL")

if else statement example output in Rstudio

This code can also be written in a single line 

> if (score > 50)  print('PASS')  else  print('FAIL')

if else in R programming allows us to use this statement in this way also

>age <- 19

>status <- if(age > 18) "Adult" else "Child"

>[1] "Adult"

First we are assigning 19 to a variable named age

Then we are creating a new variable status, however the value assigned to it depends on a condition. If the age variable is more than 18 then "Adult" will be assigned to status, otherwise "Child" will be assigned to it. In our example the variable age is 19, hence status will be assigned "Adult" string, which is shown in output. This construct makes the code neat and more readable.

This method can also be used with if statement also

>score <- 55

>Grade <- if(score > 50) "PASS"

>[1] "PASS"

The if...else if...else statement

The syntax of if...else if...else is 

if (condition no 1) {

    //code to be executed if condition no 1 is True

} else if(condition no 2) {

    //code to be executed if condition no 2 is True

} else if(condition no 3) {

    //code to be executed if condition no 3 is True

} else { // code to be executed if all conditions are False 

Here only one block of code will be executed depending on the condition. 

Example of nested if statement:

You have to write an R program which outputs grade when score is given to it. Lets see how it will be done and also the output using rstudio

You can see the output is "C" which is correct. You may write this program, change score to 95, 82,60 and 45 and see what is the output of the code. There are 5 possible output and you should check to see if the program is working fine. This is testing your code and debugging it for any logical errors.

After this tutorial you should be able to understand decision making in R programming which consists of if statement, if...else statement and nested if statement. These statements form the core of R programming practise variety of code exercises to have grasp over these constructs. 

R for Statistics, Data Science

  • How to Learn R
  • R Hello World!
  • Set working directory
  • if else statement
  • Repeat Loop
  • R break & next
  • R Read CSV file
  • R Recursion
  • R switch function
  • ifelse() Function
  • R append() Function
  • R Standard deviation
  • R Code Examples

R Tutor Online

  • Data Visualization
  • Statistics in R
  • Machine Learning in R
  • Data Science in R
  • Packages in R

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 evaluated to be false.

The decision making statement in R are as followed:

if statement

If-else statement, if-else-if ladder.

  • nested if-else statement

switch statement

Keyword if tells compiler that this is a decision control instruction and the condition following the keyword if is always enclosed within a pair of parentheses. If the condition is TRUE the statement gets executed and if condition is FALSE then statement does not get executed.

Syntax:           if(condition is true){                 execute this statement            }

Flow Chart:                        

if-statement-flowchart

Example: 

Output: 

If-else , provides us with an optional else block which gets executed if the condition for if block is false.  If the condition provided to if block is true then the statement within the if block gets executed, else the statement within the else block gets executed.

Syntax:           if(condition is true) {               execute this statement           } else {              execute this statement            }

Flow Chart:

if-else-statement-flowchart

Example : 

It is similar to if-else statement, here the only difference is that an if statement is attached to else. If the condition provided to if block is true then the statement within the if block gets executed, else-if the another condition provided is checked and if true then  the statement within the block gets executed.

Syntax:          if(condition 1 is true) {               execute this statement          } else if(condition 2 is true) {              execute this statement          } else {              execute this statement         }

Flow Chart: 

if-else-if-ladder-flowchart

Nested if-else statement

When we have an if-else block as an statement within an if block or optionally within an else block, then it is called as nested if else statement. When an if condition is true then following child if condition is validated and if the condition is wrong else statement is executed, this happens within parent if condition. If parent if condition is false then else block is executed with also may contain child if else statement.

Syntax:  if(parent condition is true) {                if( child condition 1 is true) {                  execute this statement              } else {                  execute this statement             }      } else {             if(child condition 2 is true) {                 execute this statement             } else {                execute this statement            }      }

nested-if-else-flowchart

In this switch function expression is matched to list of cases. If a match is found then it prints that case’s value. No default case is available here. If no case is matched it outputs NULL as shown in example.

Syntax: switch (expression, case1, case2, case3,…,case n )

Flow Chart :

switch-statement-flowchart

                

Please Login to comment...

Similar reads.

  • How to Strikethrough on Discord
  • Discord Launches End-To-End Encryption For Audio & Video Chats
  • iPadOS 18 is Now Available: Complete Features and How to Install
  • Microsoft’s Latest 365 Copilot Updates: Enhanced AI Tools for Excel, PowerPoint, and Teams
  • 10 Best PrimeWire Alternatives (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

An Introduction to R programming

Chapter 2 logical expressions and if-else statements in r, 2.1 logical expression in r.

A Logical expression is an expression that evaluates to either TRUE or FALSE .

The following are examples of logical expressions in R :

  • 15.0 + 1.3*1.3 > 17.0
  • "cat" == "dog"

Each of the above expressions will evaluate to either TRUE or FALSE if you run them in R.

  • Comparison operators (<, <=, ==, !=)
  • Logical operators ( and , or , not ) (in R : &&, ||, !)

2.1.1 Comparison Operators

Operator Meaning Example Result
< Less than 5 < 3 FALSE
> Greater than 5 > 3 TRUE
<= Less than or equal to 3 <= 6 TRUE
>= Greater than or equal to 4 >= 3 TRUE
== Equal to 2 == 2 TRUE
!= Not equal to ‘str’ != ‘stR’ TRUE

2.1.2 Logical Operators

The first main logical operator we will discuss is the logical AND

In R , the logical operator & is used to represent the logical AND

The logical AND is used to test whether or not two statements are both true.

For two logical expressions A and B , the logical expression A & B is true only if both A and B evaluate to true.

The logical operator | is used in R to represent the logical OR .

For two Boolean expressions A and B , the Boolean expression A | B is true if at least one of A and B evaluates to true.

Note that if A and B are both true, A | B will be true; or does not mean only one of A and B is true.

The logical operator ! is used to represent the logical NOT .

If the logical expression A is true, then ! A is false.

  • Note that we can apply logical operations to the keywords TRUE and FALSE themselves:
  • The below table summarizes the logical operations discussed.
Operator Meaning Example Result
! Logical NOT !TRUE FALSE
!FALSE TRUE
&& Logical AND FALSE & FALSE FALSE
TRUE & FALSE FALSE
FALSE & TRUE FALSE
TRUE & TRUE TRUE
|| Logical OR FALSE | FALSE FALSE
TRUE | FALSE TRUE
FALSE | TRUE TRUE
TRUE | TRUE TRUE

2.1.3 Precedence with logical operations

Operators Meaning Precedence
&, |, ! Boolean operators Low
+, - Addition and subtraction
*, /, %% Multiplication, division, remainder
**, ^ Exponentiation
(expressions …) Parenthesis High
  • Mathematical operations are generally performed before logical operations.

2.1.4 Abbreviating TRUE and FALSE with T and F

  • I usually do not use T and F , but you will often see T and F used.
  • While you can use T and F in place of TRUE and FALSE , it is good practice to be careful when using these logical abbreviations .

2.1.5 Examples of logical operations in R

2.1.6 logical operators and vectors.

You can also apply the logical operators & , | , ! to two vectors.

As an example, let us first define two logical vectors x and y of length 4

Applying the logical operator & to x and y will apply an element-by-element logical and to the elements of x and y .

That is, running x & y will return the following result

  • Similarly, applying the logical operator | to x and y will apply an element-by-element logical or to the elements of x and y .
  • Using the logical operator ! with a vector will just return a vector where the TRUE values have been switched to FALSE and the FALSE values have been switched to TRUE :

2.1.7 && vs. & and || vs. |

I would suggest using & for the logical AND operator and | for the logical OR operator.

You may sometimes see && and || being used in R code.

&& and || can only be used for comparing vectors of length 1.

  • For vectors of length 1, they do the exact same thing as & and |

For example,

2.2 If and If-else statements

2.2.1 if statements.

  • In R , the form of an if statement is the following:

condition is usually a logical expression , but could just be a logical vector of length 1 (i.e., TRUE or FALSE).

If condition evaluates to TRUE , code_chunk1 will be executed.

You actually do not have to indent the code in code_chunk1 , but I would recommend that you do indent.

The code inside {…} will be executed only if the condition of the if statement is TRUE.

2.2.2 if statement examples

  • Example 1: Running the following code will output the message in the if statement because the logical expression x < y evalutes to TRUE
  • Example 2: Running the following code will not print out anything:

2.2.3 Single-line if statements

If the code to be executed in the if statement is short, you can write it immediately after if(condition) on the same line .

Or, you can write the single-line statement on the line immediately below if(condition)

  • This single-line if statement is the same as using:

2.3 if-else statements

In many cases, you want to perform an action if a condition is true but perform another action if that condition is false.

This can be done with an if-else statement.

In R , the form of an if-else statement is the following:

As with if statements, condition is usually a logical expression, but could just be a logical vector (with a single element).

Otherwise, if condition evaluates to FALSE , code_chunk2 will be executed.

  • As an example, let’s write an if-else statement that computes the absolute value of a number.
  • Another if-else example:

2.3.1 if-else-if chains

In many cases, a desired computation will depend on more than 2 conditions.

For these cases, you can use an if - else if - else chain of conditional statements.

The general syntax for an if - else if - else chain in R is:

  • An if-else if-else example:
  • Another if-else if-else example:

Be careful about the location of else in if-else if-else statements

In R , you do not want to start a line with else if or else .

For example, the following if-else statement will not run

2.3.2 Nested if-else statements

  • You can certainly have if-else statements within a conditional statement.

2.4 The ifelse function

  • The ifelse function is a useful function that acts as a “vectorized” if-else statement.

2.5 Exercises

  • What will be printed to the screen if you run the R code below?
  • What number will be printed to the screen if you run the R code below?
  • What will the value of the variable z be after running the following code:

R if else elseif Statement

Often, you need to execute some statements only when some condition is met. You can use following conditional statements in your code to do this.

  • if Statement: use it to execute a block of code, if a specified condition is true
  • else Statement: use it to execute a block of code, if the same condition is false
  • else if Statement: use it to specify a new condition to test, if the first condition is false
  • ifelse() Function: use it when to check the condition for every element of a vector

The if Statement

Use if statement to execute a block of code, if the condition is true.

r if statement syntax

Making a simple comparison

Likewise, you can use following comparison operators to compare two values:

R Comparison operators with if statement
OperatorMeaningExample
==Equalsif (x == y)
!=Not equalsif (x != y)
>Greater thanif (x > y)
>=Greater than or equal toif (x >= y)
<Less thanif (x < y)
<=Less than or equal toif (x <= y)

More Examples

In R, any non-zero value is considered TRUE, whereas a zero is considered FALSE. That’s why all the below if statements are valid.

if Statement Without Curly Braces

If you have only one statement to execute, you can skip curly braces.

Nested if Statement

You can write one if statement inside another if statement to test more than one condition and return different results.

The else Statement

Use else statement to execute a block of code, if the condition is false.

r if else statement syntax

condition: is any expression that evaluates to either true or false.

if statement: specifies a block of statements if the condition is true.

else statement: specifies a block of statements if the condition is false.

A Simple if-else comparison

The else if statement.

Use else if statement to specify a new condition to test, if the first condition is false.

r if else if else statement syntax

elif statement: specifies a new condition to test, if the first condition is false.

Using else-if Statement

In R, you can use as many else if statements as you want in your program. There’s no limit. However, it’s not a best practice when you want to make series of decisions. You can use switch() function as an efficient way.

Multiple Conditions

To join two or more conditions into a single if statement, use logical operators viz. && (and), || (or) and ! (not).

&& (and) expression is True, if all the conditions are true.

|| (or) expression is True, if at least one of the conditions is True.

! (not) expression is True, if the condition is false.

One Line If…Else

If you have only one statement to execute, one for if , and one for else , you can put it all on the same line:

r one line if else syntax

You can also use it to select variable assignment.

The ifelse() Function

In R, conditional statements are not vector operations. They deal only with a single value.

If you pass in, for example, a vector, the if statement will only check the very first element and issue a warning.

The solution to this is the ifelse() function. The ifelse() function checks the condition for every element of a vector and selects elements from the specified vector depending upon the result.

Here’s the syntax for the ifelse() function.

r ifelse function syntax

You can even use this function to choose values from two vectors.

Popular Tutorials

Popular examples, learn python interactively, r introduction.

  • R Reserved Words
  • R Variables and Constants

R Operators

  • R Operator Precedence and Associativitys

R Flow Control

  • R if…else Statement

R ifelse() Function

  • R while Loop
  • R break and next Statement
  • R repeat loop
  • R Functions
  • R Return Value from Function
  • R Environment and Scope
  • R Recursive Function
  • R Infix Operator
  • R switch() Function

R Data Structures

  • R Data Frame

R Object & Class

  • R Classes and Objects
  • R Reference Class

R Graphs & Charts

  • R Histograms
  • R Pie Chart
  • R Strip Chart

R Advanced Topics

  • R Plot Function
  • R Multiple Plots
  • Saving a Plot in R
  • R Plot Color

Related Topics

R if else Statement

R Program to Add Two Vectors

In this article, you will learn about the ifelse() function in R programming with the help of examples.

Vectors form the basic building block of R programming. Most of the functions in R take vectors as input and output a resultant vector.

This vectorization of code will be much faster than applying the same function to each element of the vector individually.

Similar to this concept, there is a vector equivalent form of the if…else statement in R, the ifelse() function.

The ifelse() function is a conditional function in R that allows you to perform element-wise conditional operations on vectors or data frames.

  • Syntax of ifelse() function

The syntax of the ifelse() function is:

  • text_expression - A logical condition or a logical vector that specifies the condition to be evaluated. It can be a single logical value or a vector of logical values.
  • x - The value or expression to be returned when the condition is true. It can be a single value, vector, or an expression.
  • y - The value or expression to be returned when the condition is false. It can be a single value, vector, or an expression.

The return value is a vector with the same length as test_expression .

This is to say, the ith element of the result will be x[i] if test_expression[i] is TRUE else it will take the value of y[i] .

  • Example: ifelse() function

In the example, a is a vector with values [5, 7, 2, 9] .

When we apply the condition a %% 2 == 0 , it checks each element in a to see if it is divisible by 2 without a remainder. This results in a logical vector: [FALSE, FALSE, TRUE, FALSE] .

Now, the ifelse() function takes this logical vector as the condition. It also takes two other vectors: ["even", "even", "even", "even"] and ["odd", "odd", "odd", "odd"] .

Since the condition vector has a length of 4 , the other two vectors are recycled to match this length.

The ifelse() function then evaluates each element of the condition vector. If the element is TRUE , it chooses the corresponding element from the "even" vector. If the element is FALSE , it chooses the corresponding element from the "odd" vector.

Table of Contents

  • Introduction

Sorry about that.

R Tutorials

Programming

if else in r multiple assignments

Vectorised if-else

if_else() is a vectorized if-else . Compared to the base R equivalent, ifelse() , this function allows you to handle missing values in the condition with missing and always takes true , false , and missing into account when determining what the output type should be.

A logical vector

Vectors to use for TRUE and FALSE values of condition .

Both true and false will be recycled to the size of condition .

true , false , and missing (if used) will be cast to their common type.

If not NULL , will be used as the value for NA values of condition . Follows the same size and type rules as true and false .

These dots are for future extensions and must be empty.

An optional prototype declaring the desired output type. If supplied, this overrides the common type of true , false , and missing .

An optional size declaring the desired output size. If supplied, this overrides the size of condition .

A vector with the same size as condition and the same type as the common type of true , false , and missing .

Where condition is TRUE , the matching values from true , where it is FALSE , the matching values from false , and where it is NA , the matching values from missing , if provided, otherwise a missing value will be used.

R-bloggers

R news and tutorials contributed by hundreds of R bloggers

If ifelse() had more if’s.

Posted on October 11, 2019 by kaijagahm in R bloggers | 0 Comments

[social4i size="small" align="align-left"] --> [This article was first published on woodpeckR , and kindly contributed to R-bloggers ]. (You can report issue about the content on this page here ) Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

The ifelse() function only allows for one “if” statement, two cases. You could add nested “if” statements, but that’s just a pain, especially if the 3+ conditions you want to use are all on the same level, conceptually. Is there a way to specify multiple conditions at the same time?

I was recently given some survey data to clean up. It looked something like this (but obviously much larger):

tabletest.png

I needed to classify people in this data set based on whether they had passed or failed certain tests.

I wanted to separate the people into three groups:

  • People who passed both tests: Group A
  • People who passed one test: Group B
  • People who passed neither test: Group C

I thought about using a nested ifelse  statement, and I certainly could have done that. But that approach didn’t make sense to me. The tests are equivalent and not given in any order; I simply want to sort the people into three equal groups. Any nesting of “if” statements would seem to imply a hierarchy that doesn’t really exist in the data. Not to mention that I hate nesting functions. It’s confusing and hard to read. 

Once again, dplyr to the rescue! I’m becoming more and more of a tidyverse fan with each passing day. 

Turns out, dplyr has a function for exactly this purpose: case_when() . It’s also known as “a general vectorised if,” but I like to think of it as “if ifelse() had more if’s.” 

Here’s the syntax:

tabletest2.PNG

Let me translate the above into English. After loading the package, I reassign df , the name of my data frame, to a modified version of the old df . Then ( %>% ), I use the mutate  function to add a new column called group . The contents of the column will be defined by the case_when()  function.

case_when() , in this example, took three conditions, which I’ve lined up so you can read them more easily. The condition is on the left side of the ~ , and the resulting category (A, B, or C) is on the right. I used logical operators for my conditions. The newest one to me was the xor()  function, which is an  exclusive or : only one of the conditions in the parentheses can be TRUE, not both. 

Easily make conditional assignments within a data frame. This function is a little less succinct than ifelse() , so I’m probably not going to use it for applications with only two cases, where ifelse()  would work fine. But for three or more cases, it can’t be beat. Notice that I could have added any number of conditions to my case_when()  statement, with no other caveats.

I love this function, and I think we should all be using it.

To leave a comment for the author, please follow the link and comment on their blog: woodpeckR . R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job . Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Copyright © 2022 | MH Corporate basic by MH Themes

Never miss an update! Subscribe to R-bloggers to receive e-mails with the latest R posts. (You will not see this message again.)

if_else: Vectorised if

Description.

Compared to the base ifelse() , this function is more strict. It checks that true and false are the same type. This strictness makes the output type more predictable, and makes it somewhat faster.

Where condition is TRUE , the matching value from true , where it's FALSE , the matching value from false , otherwise NA .

Logical vector

Values to use for TRUE and FALSE values of condition . They must be either the same length as condition , or length 1. They must also be the same type: if_else() checks that they have the same type and same class. All other attributes are taken from true .

If not NULL , will be used to replace missing values.

Run the code above in your browser using DataLab

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Using ifelse statement for multiple values in a column

I have a table with approximately 3000 rows with data in the form of :

I want to add a third column so that the table looks like :

where values in the SCHEach column are based on values in the Type column. If values in the Type column are 16,17,21, or 22, values in the SCHeach column should be 1. For any other values in the Type column, SCHEach values should be 0.

Right now I'm using the following

I am new to R and wanted to know if there is a way to do it without having to type the following separately for 16,17,21,and 22?

  • if-statement

user6340762's user avatar

  • 2 Read about %in% , type ?match in the console. –  zx8754 Commented Oct 30, 2016 at 14:56
  • 2 Try schtable <- schtable %>% mutate(SCHEac = if_else(Type %in% c(16,17,21,22), 1, 0)) –  zx8754 Commented Oct 30, 2016 at 15:03
  • Thanks! @zx8754 That worked well. –  user6340762 Commented Oct 30, 2016 at 15:12
  • 2 You don't need a ifelse schtable %>% mutate(SCHEac = as.integer(Type %in% c(16, 17, 21, 22))) –  akrun Commented Oct 30, 2016 at 15:13

akaDrHouse's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged r if-statement dplyr or ask your own question .

  • The Overflow Blog
  • Detecting errors in AI-generated code
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Preventing unauthorized automated access to the network
  • Announcing the new Staging Ground Reviewer Stats Widget

Hot Network Questions

  • Would all disagreements vanish if everyone had access to the same information and followed the same reasoning process?
  • Crime and poverty: Correlation or causation?
  • How can I edit files in `/sys/kernel/mm/ksm/` to survive reboots?
  • Tomatoes measured in quarts
  • Why does Leviticus 11 say that the rabbit chews the cud?
  • What is this general prohibition/slash symbol on my Xcode app
  • Change style of True/False everywhere
  • The King takes a stroll
  • Generic C++ Class to Associate enum Values with Strings for Translation
  • Letter of recommendation conflict of interest
  • How to solve this partial differential equation for y?
  • BSS138 level shifter - blocking current flow when high-side supply is not connected?
  • Why is thermal conductivity of thermal interface materials so low?
  • How to find all local minima in a range for a complicated function quickly?
  • Is Wild Shape affected by Moonbeam?
  • Can Ubuntu 24.04 be compromised?
  • How to implement a "scanner" effect on Linux to fix documents with varying darkness of background?
  • Why is China's Tiangong space station inaccessible from Russia's launch sites?
  • How can I have my paper reviewed?
  • SF story set in an isolated (extragalactic) star system
  • Why does lottery write "in trust" on winner's cheque?
  • Why doesn't Spacex use a normal blast trench like Saturn V?
  • He worked in the field during most of the day
  • How fast to play Rachmaninoff’s Études-Tableaux, Op. 33 No. 5 in G minor?

if else in r multiple assignments

COMMENTS

  1. r

    You can think about ifelse() in R as a function that operates on 3 vectors: vector of boolean values (TRUE, FALSE). This is the 1==3 | 2==2 | 3==3 part. vector of elements that will be chosen when the first vector is TRUE. This is the a <- 100 part. vector of elements that will be chosen when the first vector is FALSE.

  2. If statement with multiple actions in R

    You should use the semicolon. The last statement is the return value. EDIT This works for multiple statements, too. You can omit the semicolon if you use line breaks, as in. c<-1000. d<-1500. e <- 2000. EDIT: this should work with ifelse too. You would have to keep in mind that you are operating on a vector, though.

  3. How to Write a Nested If Else Statement in R (With Examples)

    This simple ifelse statement tells R to do the following: If the value in the team column is 'A' then give the player a rating of 'great.' Else, give the player a rating of 'bad.' Example 2: How to Write a Nested If Else Statement. The following code shows how to create a new column in the data frame by writing a nested if else ...

  4. R: How to Use If Statement with Multiple Conditions

    This tutorial explains how to use an if else statement with multiple conditions in R, including an example. About; Course; Basic Stats; Machine Learning; Software Tutorials. Excel; Google Sheets ... You can use the following methods to create a new column in R using an IF statement with multiple conditions: Method 1: If Statement with Multiple ...

  5. The Ultimate Guide to Conditional Statements in R

    If this x is smaller than zero, we want R to print out "x is a negative number". We can do this by using the if statement. We first assign the variable x, and then write the if condition. In this case, assign -3 to x, and set the if condition to be true if x is smaller than 0 (x < 0 ).

  6. If Else Conditions in R (with Examples)

    If Else in Popular R Packages. Other than base R, there are functions available in packages for If Else conditions. dplyr: If Else. Below is the syntax of if_else( ) function of dplyr package in R. if_else(condition, value if condition is true, value if condition is false, value if NA) Example 1: Using if_else() to create a new column.

  7. R if else Statement (With Examples)

    There is an easier way to use the if else statement specifically for vectors in R programming. You can use the ifelse() function instead; the vector equivalent form of the if else statement. Check out these related examples: Find the Factorial of a Number. Check Prime Number. Check Armstrong Number.

  8. How to Use If-Else Statements and Loops in R

    In R, an if-else statement tells the program to run one block of code if the conditional statement is TRUE, and a different block of code if it is FALSE. Here's a visual representation of how this works, both in flowchart form and in terms of the R syntax: ****** **. To generalize, if-else in R needs three arguments:

  9. How to Write Conditional Statements in R: Four Methods

    The big difference here is that we now assign the result of the whole conditional statement to the variable age_group. This improves on the repetitive phrasing in the standard if-else example, where we had to write this assignment twice. Base-R ifelse function. If you prefer, you can use the ifelse function instead. The code below uses this ...

  10. R: ifelse statements with multiple variables and NAs

    The code to do the new variable construction is below. We are constructing the 24th variable, which is named C1x*: The first ifelse gives the value 1 to the new variable if the respondent picked this response option, with the !is.na () preventing problems arising from NA values in Other.Source.

  11. R if...else statement (With Examples & Flowchart)

    This is done in R using if & if...else statement. R if statement. if statement is used when there is only one test condition and on the basis of that you have to take a decision. First the condition is checked. If the boolean expression results in to True the body of if statement is executed, otherwise R code in the specific block is skipped. ...

  12. Decision Making in R Programming

    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 sta

  13. Chapter 2 Logical Expressions and If-Else Statements in R

    2.3 if-else statements. In many cases, you want to perform an action if a condition is true but perform another action if that condition is false. This can be done with an if-else statement. In R, the form of an if-else statement is the following:

  14. R if else elseif Statement

    In R, you can use as many else if statements as you want in your program. There's no limit. However, it's not a best practice when you want to make series of decisions. You can use switch() function as an efficient way. Multiple Conditions. To join two or more conditions into a single if statement, use logical operators viz. && (and ...

  15. R ifelse() Function (With Examples)

    Example: ifelse () function. # check if each element in a is even or odd. Output. In the example, a is a vector with values [5, 7, 2, 9]. When we apply the condition a %% 2 == 0, it checks each element in a to see if it is divisible by 2 without a remainder. This results in a logical vector: [FALSE, FALSE, TRUE, FALSE].

  16. Vectorised if-else

    Vectorised if-else. Source: R/if-else.R. if_else() is a vectorized if-else. Compared to the base R equivalent, ifelse(), this function allows you to handle missing values in the condition with missing and always takes true, false, and missing into account when determining what the output type should be.

  17. if ifelse() had more if's

    Problem The ifelse() function only allows for one "if" statement, two cases. You could add nested "if" statements, but that's just a pain, especially if the 3+ conditions you want to use are all on the same level, conceptually. Is there a way to specify multiple conditions at the same time? Context I was recently … Continue reading "if ifelse() had more if's"

  18. using ifelse in r with multiple returns

    As answered here: If statement with multiple actions in R, for the block IF statement, the ELSE should be on the same line as the previous curly bracket. So, instead of. y = 2. t = 3. y = 0. t = 0. the format should be (the ELSE is on the same line as the previous curly bracket) y = 2. t = 3.

  19. if_else function

    Values to use for TRUE and FALSE values of condition. They must be either the same length as condition, or length 1. They must also be the same type: if_else() checks that they have the same type and same class. All other attributes are taken from true. If not NULL, will be used to replace missing values.

  20. Using ifelse statement for multiple values in a column

    I am new to R and wanted to know if there is a way to do it without having to type the following separately for 16,17,21,and 22? ... r if else based on multiple conditions. 30. Ifelse statement in R with multiple conditions. 0. Use ifelse statement on multiple columns based on column name. 5.