Loops 演示
重复运行同一个命令集
Setup
What is a loop?
In R, loops are control structures used to repeat a block of code multiple times until a certain condition is met. Loops are useful when you want to perform repetitive tasks or iterate over elements in a vector, list, or data frame.
A simple xxample
[1] "Luke Skywalker"
[1] "C-3PO"
[1] "R2-D2"
[1] "Darth Vader"
[1] "Leia Organa"
[1] "Luke Skywalker"
[1] "C-3PO"
[1] "R2-D2"
[1] "Darth Vader"
[1] "Leia Organa"
Another example
[1] 172
[1] 167
[1] 96
[1] 202
[1] 150
[1] 178
[1] 165
[1] 97
[1] 183
[1] 182
[1] 188
[1] 180
[1] 228
[1] 180
[1] 173
[1] 175
[1] 170
[1] 180
[1] 66
[1] 170
[1] 183
[1] 200
[1] 190
[1] 177
[1] 175
[1] 180
[1] 150
[1] NA
[1] 88
[1] 160
[1] 193
[1] 191
[1] 170
[1] 185
[1] 196
[1] 224
[1] 206
[1] 183
[1] 137
[1] 112
[1] 183
[1] 163
[1] 175
[1] 180
[1] 178
[1] 79
[1] 94
[1] 122
[1] 163
[1] 188
[1] 198
[1] 196
[1] 171
[1] 184
[1] 188
[1] 264
[1] 188
[1] 196
[1] 185
[1] 157
[1] 183
[1] 183
[1] 170
[1] 166
[1] 165
[1] 193
[1] 191
[1] 183
[1] 168
[1] 198
[1] 229
[1] 213
[1] 167
[1] 96
[1] 193
[1] 191
[1] 178
[1] 216
[1] 234
[1] 188
[1] 178
[1] 206
[1] NA
[1] NA
[1] NA
[1] NA
[1] NA
Example 3
代码
[1] 1.72 1.67 0.96 2.02 1.50
Creating a break
A loop can be stopped if certain criteria are met. In the example below, when looping through the vector, R will break the loop as soon as × is equal to “Darth Vader”.
[1] "Luke Skywalker"
[1] "C-3PO"
[1] "R2-D2"
[1] "Darth Vader"
Concatenate and print
This is a lovely feature of looping that allows you to create a text output that is driven by differences in each iteration. The cat) function allows you to concatenate (or join together) elements of text.
Let’s take a look.