dplyr mutate Function with Logical ifelse Condition in R (2 Examples)

 

In this tutorial you’ll learn how to use the mutate function with a logical condition in the R programming language.

Table of contents:

Let’s take a look at some R codes in action…

 

Example Data & Packages

Consider the following example data:

data <- data.frame(x1 = 1:5,    # Example data
                   x2 = letters[1:5],
                   x3 = 3)
data                            # Print example data
#   x1 x2 x3
# 1  1  a  3
# 2  2  b  3
# 3  3  c  3
# 4  4  d  3
# 5  5  e  3

The previous output of the RStudio console shows that our example data consists of five rows and three columns.

For the examples of this tutorial, I also have to install and load the dplyr package of the tidyverse:

install.packages("dplyr")       # Install & load dplyr
library("dplyr")

Let’s move on to the examples…

 

Example 1: Conditional mutate Function Returns Logical Value

The following R programming syntax shows how to use the mutate function to create a new variable with logical values. For this, we need to specify a logical condition within the mutate command:

data %>%                        # Apply mutate
  mutate(x4 = (x1 == 1 | x2 == "b"))
#   x1 x2 x3    x4
# 1  1  a  3  TRUE
# 2  2  b  3  TRUE
# 3  3  c  3 FALSE
# 4  4  d  3 FALSE
# 5  5  e  3 FALSE

The condition we have specified within the mutate function is TRUE for rows 1 and 2. Hence, our new variable x4 contains the value TRUE in these rows.

 

Example 2: Conditional mutate Function Returns Numeric Value

We can also add a numeric variable reflecting the outcome of our logical condition. We simply need to multiply our condition with 1:

data %>%                        # Apply mutate
  mutate(x4 = (x1 == 1 | x2 == "b") * 1)
#   x1 x2 x3 x4
# 1  1  a  3  1
# 2  2  b  3  1
# 3  3  c  3  0
# 4  4  d  3  0
# 5  5  e  3  0

 

Video, Further Resources & Summary

If you need further explanations on the topics of this tutorial, you may want to watch the following video of my YouTube channel. I illustrate the R syntax of this tutorial in the video:

 

The YouTube video will be added soon.

 

Furthermore, I can recommend to read the related tutorials on Statistics Globe. A selection of tutorials is listed here.

 

To summarize: This tutorial illustrated how to apply the mutate function with an ifelse condition in the R programming language. If you have further questions and/or comments, tell me about it in the comments.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


2 Comments. Leave new

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Top