Case when in R

R provides us case_when() function using which we can implement case when in R. It is equivalent to “case when” statement in SQL.

Syntax:

case_when(expression)

 Here, 

  • expression: It represent a condition expression

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 example, suppose we want to check whether a candidate is eligible to cast a vote.  To solve this problem, we can evaluate his age and if it is greater than 18 we will allow him to vote otherwise he is not eligible. 

Similar Reads

Case when in R:

R provides us case_when() function using which we can implement case when in R. It is equivalent to “case when” statement in SQL....

Method 1: Create a new variable after executing  the case when statement and using mutate function:

Mutate function in R is used to add newly created variables and it also preserves the existing variables....

Method 2: Handling NA using Case when statement

...

Method 3: Using switch statement in R

Look into the Price column of the data_frame that we have created above once again. Some cars have a price value equal to NA. While applying case_when() function, this must be handled carefully. R provides us is.na() function using which we can handle na values....

Method 4: Using case_when in vector

...

Contact Us