-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathforloop.Rmd
58 lines (44 loc) · 1.18 KB
/
forloop.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
# Repetitive execution
**Loops** are used to repeat a specific block of code.
<br>
Structure of the **for loop**:
```{r, eval=F}
for(i in vector_expression){
action_command
}
```
3 main elements:
* **i** is the loop variable: it is updated at each iteration.
* **vector_expression**: value attributed to **i** at each iteration (the number of iterations is the **length of vector_expression**).
* **action_command**: what is to be done at each iteration.
Note the usage of **curly brakets {}** to start and end the loop!
<br><br>
<img src="images/forloop1.png" width="300"/><img src="images/forloop2.png" width="450"/>
* Example:
```{r}
for(i in 2:5){
y <- i*2
print(y)
}
```
* Example of a **for loop** that iterates over a character vector:
```{r}
# Character vector
myfruits <- c("apple", "pear", "grape")
# For loop that prints the current element and its number of characters
for(j in myfruits){
print(j)
print(nchar(j))
}
```
* Example of a **for loop** that iterates over each row of a matrix, and prints the minimum value of that row :
```{r}
# Matrix
mymat <- matrix(rnorm(800),
nrow=50)
# For loop over mymat rows
for(i in 1:nrow(mymat)){
print(i)
print(min(mymat[i,]))
}
```