-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path3-7_functions_looping.qmd
119 lines (91 loc) · 3.17 KB
/
3-7_functions_looping.qmd
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
# Looping {.unnumbered}
Loops are used to iterate (repeat) an R statement (or set of statements). They're implemented in three ways, `for()`, `while()`, and `repeat()`, but the most often used are `for()` loops:
```{r,eval=FALSE}
for() # Repeat a set of statements a specified number of times
while() # Repeat a set of statements as long as a specified condition is met
repeat # Repeat a set of statements until a break command is encountered
```
Two other commands, break and next, are used, respectively, to terminate a loop's iterations and to skip ahead to the next iteration:
```{r, eval=FALSE}
break # Terminate a loops iterations
next # Skip ahead to the next iteration
```
Here's an example in which each of the three loop types, for(), while(), and repeat, are used to perform a simple task, namely printing the numbers 1\^2; 2\^2; ...; 5\^2 to the screen:
```{r}
for(i in 1:5) {
print(i^2)
}
```
```{r}
i <- 1
while(i <= 5) {
print(i^2)
i <- i + 1
}
```
```{r}
i <- 1
repeat {
print(i^2)
i <- i + 1
if(i > 5) break
}
```
## for() Loops
`for()` loops are used when we know in advance how many iterations the loop should perform. The general form of a `for()` loop is:
```{r, eval=F}
for(i in sequence) {
statement1
statement2
.
.
.
statementq
}
```
where `sequence` is a vector, `i` (whose name you're free to change) assumes the values in sequence one after another, each time triggering another iteration of the loop during which statements 1 through q are executed. The statements usually involve the variable `i`.
Here's an example. Suppose we have the data frame describing someone's coin collection:
```{r}
coins <- data.frame(Coin = c("penny", "quarter", "nickel", "quarter", "dime", "penny"),
Year = c(1943, 1905, 1889, 1960, 1937, 1900),
Mint = c("Den", "SF", "Phil", "Den", "SF", "Den"),
Condition = c("good", "fair", "excellent", "good", "poor", "good"),
Value = c(12.00, 55.00, 300.00, 40.00, 18.00, 28.00),
Price = c(15.00, 45.00, 375.00, 25.00, 20.00, 20.00))
coins
```
If we type:
```{r, error=TRUE}
colMeans(coins)
```
we get an error message because some of the columns are non-numeric. We can compute the means of the numeric columns by looping over the columns, each time checking whether it's numeric before computing it's mean:
```{r}
means <- NULL
for(i in 1:ncol(coins)) {
if (is.numeric(coins[ , i])) {
means <- c(means, mean(coins[ , i]))
}
}
```
The result is:
```{r}
means
```
## Looping Over List Elements
In the next example, we loop over the elements of a list, printing a list element and recording it's length during each iteration:
```{r}
myList <- list(
w = c(4, 4, 5, 5, 6, 6),
x = c("a", "b", "c"),
y = c(5, 10, 15),
z = c("r", "s", "t", "u", "v")
)
lengths <- NULL
for(i in myList) {
print(i)
lengths <- c(lengths, length(i))
}
lengths
```
These examples are very simple, but looping is a very powerful programming structure for automating analyses, or data processing.
In the next chapter we will look at the `apply()` family of functions, that have been designed for applying functions to a data set in several convenient ways.