-
Notifications
You must be signed in to change notification settings - Fork 0
/
r4.1-conditionals.Rmd
165 lines (133 loc) · 3.55 KB
/
r4.1-conditionals.Rmd
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
---
title: "Conditionals"
output:
html_document:
number_sections: false
toc: yes
---
```{r child = file.path("child", "setup.Rmd")}
```
> ### Learning Objectives
>
> * Understand how to use `if` and `else` statements to handle conditional programming.
>
> ### Suggested Readings
>
> * [Chapters 9.2 - 9.3](https://rstudio-education.github.io/hopr/programs.html#if-statements) of "Hands-On Programming with R", by Garrett Grolemund
---
Like most programming languages, R can evaluate **conditional statements**. A conditional statement is a switch - it tells the code which command to execute depending on a _condition_ that is specified by the programmer.
The most prominent examples of a conditional statement is the `if` statement, and the accompanying `else` statement.
---
# if
The basic format of an `if` statement in R is as follows:
```
if ( CONDITION ) {
STATEMENT1
STATEMENT2
ETC
}
```
If the condition is `TRUE`, then R will execute the statements contained in the curly braces, otherwise it will skip it. This schematic illustrates the idea:
<center>
![](images/condition_if.png){ width=400 }
</center>
## Example 1
```{r}
f <- function(x) {
cat("A")
if (x == 0) {
cat("B")
cat("C")
}
cat("D")
}
```
```{r}
f(0)
f(1)
```
## Example 2
Consider a simple absolute value function. Since `abs()` is a built-in function, we'll call ours `absValue()`:
```{r}
absValue <- function(x) {
if (x < 0) {
x = -1*x
}
return(x)
}
```
```{r}
absValue(7) # Returns 7
absValue(-7) # Also returns 7
```
# if else
You can extend the `if` statement to include an `else` statement as well, leading to the following syntax:
```
if ( CONDITION ) {
STATEMENT1
STATEMENT2
ETC
} else {
STATEMENT3
STATEMENT4
ETC
}
```
The interpretation of this version is similar. If the condition is `TRUE`, then the contents of the first block of code are executed; but if it is `FALSE`, then the contents of the second block of code are executed instead. The schematic illustration of an if-else construction looks like this:
<center>
![](images/condition_if_else.png){ width=500 }
</center>
## Example
```{r}
f <- function(x) {
cat("A")
if (x == 0) {
cat("B")
cat("C")
}
else {
cat("D")
if (x == 1) {
cat("E")
} else {
cat("F")
}
}
cat("G")
}
```
```{r}
f(0)
f(1)
f(2)
```
# else if
You can also chain multiple `else if` statements together for a more complex conditional statement. For example, if you're trying to assign letter grades to a numeric test score, you can use a series of `else if` statements to search for the bracket the score lies in:
```{r}
getLetterGrade <- function(score) {
if (score >= 90) {
grade = "A"
} else if (score >= 80) {
grade = "B"
} else if (score >= 70) {
grade = "C"
} else if (score >= 60) {
grade = "D"
} else {
grade = "F"
}
return(grade)
}
```
```{r}
cat("103 -->", getLetterGrade(103))
cat(" 88 -->", getLetterGrade(88))
cat(" 70 -->", getLetterGrade(70))
cat(" 61 -->", getLetterGrade(61))
cat(" 22 -->", getLetterGrade(22))
```
---
**Page sources**:
Some content on this page has been modified from other courses, including:
- CMU [15-112: Fundamentals of Programming](http://www.kosbie.net/cmu/spring-17/15-112/notes/notes-conditionals.html), by [David Kosbie](http://www.kosbie.net/cmu/) & [Kelly Rivers](https://hcii.cmu.edu/people/kelly-rivers)
- Danielle Navarro's website ["R for Psychological Science"](https://psyr.org/index.html)