How to use case_when in vector In R Language
R also provides the facility to use case_when for manipulating a vector.
Example:
Consider the below source code. In this example, we are first checking whether the current value in the vector is divisible by 4, and if it is so then we are he replacing the multiples of 4 with the string “Yes”.
Example:
R
# R program using case_when() function to manipulate a vector # Importing library library (dplyr) # Creating a vector vector <- seq (2, 20, by = 2) # Using case_when() function case_when ( # If the value is divisible by 4 # then replace it with "Yes" vector %% 4 == 0 ~ "Yes" , TRUE ~ as.character (vector) ) |
Output:
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.
Contact Us