-
Notifications
You must be signed in to change notification settings - Fork 0
/
2020.06.10.case_when_tutorial.R
86 lines (46 loc) · 1.86 KB
/
2020.06.10.case_when_tutorial.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# Hello World
# Below is a case when tutorial
#********************************
# Libraries
#********************************
library(dplyr)
# _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _|
#********************************
# Table of Contents
#********************************
# 1.0 Introduction
# 2.0 Bringing in Data
# 3.0 Creating a new expression
# _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _|
#********************************
# 1.0 Introduction
#********************************
# Case when in R can be executed with case_when()
# function in dplyr package. Dplyr package is provided with case_when()
# function which is similar to case when statement in SQL.
# We will be using iris data to depict the example of case_when()
# function.
# _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _|
#********************************
# 2.0 My data
#********************************
mydata2 <-iris
head(mydata2)
# _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _|
#********************************
# 3.0 New Conditional Statement
#********************************
# Create new/additional variable
# species_new using the mutate function and case when statement
mydata2 %>% mutate(species_new = case_when(is.na(Species) ~ "missing",
Species=="setosa" ~ "setosa_new",
Species=="versicolor" ~ "versicolor_new",
Species=="virginica" ~ "virginica_new",
TRUE ~ "others"))
# you can use variables directly within the case_when()wrapper
# TRUE equivalent to ELSE statement
mydata2
head(mydata2)
#********************************
# End of Document | End of Script
#********************************