How to use switch statement in R In R Language
R allows us to use sapply() with a switch statement to construct a new variable that can exist as a column in the data frame.
Example:
In this example, we are We have created an additional column with the name “Vehicle_Type” we are using sapply() function with a switch statement and for respective Brands, we are marking the values of the at the corresponding position of the Vehicle_Type column as “Car”.
R
# R program using case_when through sapply() function # Import the library library (dplyr) # Creating a dataframe data_frame = data.frame (Brand = c ( "Maruti Suzuki" , "Tata Motors" , "Mahindra" , "Mahindra" , "Maruti Suzuki" ), Car = c ( "Swift" , "Nexon" , "Thar" , "Scorpio" , "WagonR" ), Price = c (400000,1000000,500000,1200000, NA ), Tax = c (2000,4000,2500,5000,3500)) # Case_when() to create new variable data_frame$Vehicle_Type <- sapply (data_frame$Brand, switch, "Tata Motors" = 'Car' , "Mahindra" = 'Car' , "Maruti Suzuki" = 'Car' ) data_frame |
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