-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathconditional.Rmd
115 lines (92 loc) · 2.02 KB
/
conditional.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
# Conditional statement
<br>
<h3>"if" statement</h3>
Structure of the **if statement**:
```{r, eval=F}
if(condition){
action_command
}
```
If the **condition** is TRUE, then proceed to the **action_command**; if it is FALSE, nothing happens.
<br>
```{r, eval=F}
k <- 10
# print if value is > 3
if(k > 3){
print(k)
}
# print if value is < 3
if(k < 3){
print(k)
}
```
<h4>With **else**</h4>
```{r, eval=F}
if(condition){
action_command1
}else{
action_command2
}
```
If the **condition** is TRUE, then proceed to the **action_command1**; if the **condition** is FALSE, proceed to **action_command2**.
```{r, eval=F}
k <- 3
if(k > 3){
print("greater than 3")
}else{
print("less than 3")
}
```
<h4>With **else if**</h4>
```{r, eval=F}
if(condition1){
action_command1
}else if(condition2){
action_command2
}else{
action_command3
}
```
<img src="images/ifelseif.png" width="450"/>
If the **condition1** is TRUE, then proceed to the **action_command1**; if the **condition1** is FALSE, test for **condition2**: if the **condition2** is TRUE, proceed to the **action_command2**; if neither **condition1** nor **condition2** are TRUE, then proceed to the **action_command3**.
<br><br>
*Note that you can add up as many **else if** statements as you want.*
* Example without **else**
```{r, eval=F}
k <- -2
# Test whether k is positive or negative or equal to 0
if(k < 0){
print("negative")
}else if(k > 0){
print("positive")
}else if(k == 0){
print("is 0")
}
```
* Example with **else**
```{r, eval=F}
k <- 10
# print if value is <= 3
if(k <= 3){
print("less than or equal to 3")
}else if(k >= 8){
print("greater than or equal to 8")
}else{
print("greater than 3 and less than 8")
}
```
* **If statement** in **For loop**:
```{r, eval=F}
# Matrix
mymat <- matrix(rnorm(800),
nrow=50)
# Loop over rows of mymat and print row if its median value is > 0
for(i in 1:nrow(mymat)){
# extract the current row
rowi <- mymat[i,]
# if median of row is > 0, print row
if(median(rowi) > 0){
print(rowi)
}
}
```