重复运行同一个命令集

作者

Reddy Lee


Setup

代码
library(tidyverse)

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

代码
for (i in 1:5) {
  print(starwars$name[i])
}
[1] "Luke Skywalker"
[1] "C-3PO"
[1] "R2-D2"
[1] "Darth Vader"
[1] "Leia Organa"
代码
for (j in 1:5) { # It does not have to be i, could be any letter
  print(starwars$name[j])
} 
[1] "Luke Skywalker"
[1] "C-3PO"
[1] "R2-D2"
[1] "Darth Vader"
[1] "Leia Organa"
代码
for (甲 in 1:5) { # 甚至汉字;注意汉字这里不能加引号。
  print(starwars$name[甲])
} 
[1] "Luke Skywalker"
[1] "C-3PO"
[1] "R2-D2"
[1] "Darth Vader"
[1] "Leia Organa"

Another example

代码
for (i in 1:length(starwars$height)) {
  print(starwars$height[i])
}
[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

代码
tallness <- vector(
  mode = "numeric",
  length = 5
)

for (i in 1:5) {
  tallness[i] <- starwars$height[i]/100
}

tallness
[1] 1.72 1.67 0.96 2.02 1.50
代码
starwars %>%
  mutate(tallness = height / 100) %>%
  select(tallness) %>% 
  head(5)
# A tibble: 5 × 1
  tallness
     <dbl>
1     1.72
2     1.67
3     0.96
4     2.02
5     1.5 

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”.

代码
for (i in starwars$name) {
  print(i)
  if (i == "Darth Vader") {
    break
  }
}
[1] "Luke Skywalker"
[1] "C-3PO"
[1] "R2-D2"
[1] "Darth Vader"
代码
for (i in starwars$name) {
  if (i == "C-3PO") {
    next # This is to skip "C-3PO"
  }
  print(i)
  if (i == "Darth Vader") {
    break
  }
}
[1] "Luke Skywalker"
[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.

代码
for (i in 1:5) {
  cat("The height of", starwars$name[i], "is", tallness[i],"meters. \n")
}
The height of Luke Skywalker is 1.72 meters. 
The height of C-3PO is 1.67 meters. 
The height of R2-D2 is 0.96 meters. 
The height of Darth Vader is 2.02 meters. 
The height of Leia Organa is 1.5 meters. 
回到顶部