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.
- mutate & transmute R Functions of dplyr Package
- dplyr Package in R
- If and Else Statements in R
- R Functions List (+ Examples)
- The R Programming Language
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.
Statistics Globe Newsletter
2 Comments. Leave new
Thank you so much for this! I suck at maths but have to learn R Studio for psychology and this helped a lot.
Hey Katy,
thanks a lot for your feedback and all the best with your psychology studies!
Regards,
Matthias