-
Notifications
You must be signed in to change notification settings - Fork 1
/
forloop.Rmd
91 lines (68 loc) · 2.08 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
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
# 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 action to take 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){
# prints the value of i at each iteration
print(i)
# multiplies i by 2 at each iteration
y <- i*2
# prints the value of y at each iteration
print(y)
}
```
* Example of a **for loop** that iterates over a character vector:
```{r}
# Character vector
myfruits <- c("apple", "pear", "grape")
# The for loop prints the current element j, and the number of characters of element j
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 of 50 rows, 16 columns
mymat <- matrix(rnorm(800),
nrow=50)
# For loop over mymat rows
# 1:nrow(mymat): ranges from 1 to the number of rows in the matrix: 1, 2, 3, 4, ...., 48, 49, 50
for(i in 1:nrow(mymat)){
# prints the value of i at each iteration
print(i)
# prints the minimum value of the ith row of mymat at each iteration
print(min(mymat[i,]))
}
```
* **If statement** in **For loop**:
You can combine **for loops** and **if statements**:
```{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)
}
}
```
You can also have a look at this [tutorial](https://www.datacamp.com/community/tutorials/tutorial-on-loops-in-r), to know more about loops.