3.3 Case Statement

20200421 Many languages support a case or switch statement. R did not originally have a case statement but it was introduced through tidyr as dplyr::case_when():

library(dplyr)

with(ds %>% sample_n(100),
     case_when(max_temp > 35 ~ "hot",
               max_temp > 25 ~ "warm",
               max_temp > 18 ~ "mild",
               max_temp > 12 ~ "cool",
               max_temp >  0 ~ "cold",
               TRUE          ~ "freezing"))
##   [1] "mild"     "mild"     "hot"      "warm"     "mild"     "mild"    
##   [7] "cool"     "warm"     "mild"     "cool"     "mild"     "cool"    
##  [13] "warm"     "cool"     "warm"     "warm"     "mild"     "warm"    
##  [19] "warm"     "mild"     "cool"     "warm"     "mild"     "warm"    
##  [25] "cool"     "warm"     "warm"     "mild"     "cool"     "cold"    
##  [31] "cool"     "mild"     "warm"     "warm"     "cool"     "warm"    
##  [37] "warm"     "cool"     "mild"     "mild"     "mild"     "mild"    
##  [43] "mild"     "warm"     "mild"     "cool"     "warm"     "cool"    
##  [49] "mild"     "warm"     "warm"     "mild"     "warm"     "warm"    
##  [55] "cool"     "mild"     "warm"     "warm"     "mild"     "cool"    
##  [61] "cool"     "mild"     "warm"     "warm"     "mild"     "mild"    
##  [67] "mild"     "cool"     "warm"     "warm"     "warm"     "cool"    
##  [73] "warm"     "warm"     "cool"     "mild"     "mild"     "mild"    
##  [79] "warm"     "warm"     "warm"     "mild"     "warm"     "mild"    
##  [85] "warm"     "mild"     "warm"     "cool"     "cool"     "cool"    
##  [91] "warm"     "warm"     "warm"     "cool"     "mild"     "cool"    
##  [97] "freezing" "warm"     "cool"     "warm"


Your donation will support ongoing development and give you access to the PDF version of this book. Desktop Survival Guides include Data Science, GNU/Linux, and MLHub. Books available on Amazon include Data Mining with Rattle and Essentials of Data Science. Popular open source software includes rattle, wajig, and mlhub. Hosted by Togaware, a pioneer of free and open source software since 1984.
Copyright © 1995-2021 Graham.Williams@togaware.com Creative Commons Attribution-ShareAlike 4.0.