From the course: Learning the R Tidyverse

Unlock the full course today

Join today to access over 24,100 courses taught by industry experts.

Use case_when() instead of nested if or ifelse()

Use case_when() instead of nested if or ifelse() - R Tutorial

From the course: Learning the R Tidyverse

Use case_when() instead of nested if or ifelse()

- [Instructor] Let's take a look at how to handle complex conditions in the tidyverse by the case_when function. I'm in the case-when.R script in the 06-02b project. I'm going to load the tidyverse in line one. Line three to four, I'm selecting out some specific columns from the msleep dataset. Line five to nine, I'm making use of the if-else function to categorize my animals by how much they sleep. At the moment, my condition is if sleep_total is less than or equal to 12, I get less than or equal to 1/2 a day asleep, and when I get more than 1/2 a day's sleep. How about if I wanted to add a condition, another condition, if it was false? So if sleep_rem was above or below a certain fraction of sleep total, you might answer that by saying, "Well, I'd nest if-else conditions." If so, I want to introduce you to a better way with case_when. So let me grab this part of the code, let me pipe it into mutate and I'm going to create a new column called sleep_category. And I'm going to use the…

Contents