重复运行同一个命令集

作者

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. 

starwars

代码
starwars
# A tibble: 87 × 14
   name     height  mass hair_color skin_color eye_color birth_year sex   gender
   <chr>     <int> <dbl> <chr>      <chr>      <chr>          <dbl> <chr> <chr> 
 1 Luke Sk…    172    77 blond      fair       blue            19   male  mascu…
 2 C-3PO       167    75 <NA>       gold       yellow         112   none  mascu…
 3 R2-D2        96    32 <NA>       white, bl… red             33   none  mascu…
 4 Darth V…    202   136 none       white      yellow          41.9 male  mascu…
 5 Leia Or…    150    49 brown      light      brown           19   fema… femin…
 6 Owen La…    178   120 brown, gr… light      blue            52   male  mascu…
 7 Beru Wh…    165    75 brown      light      blue            47   fema… femin…
 8 R5-D4        97    32 <NA>       white, red red             NA   none  mascu…
 9 Biggs D…    183    84 black      light      brown           24   male  mascu…
10 Obi-Wan…    182    77 auburn, w… fair       blue-gray       57   male  mascu…
# ℹ 77 more rows
# ℹ 5 more variables: homeworld <chr>, species <chr>, films <list>,
#   vehicles <list>, starships <list>
代码
for (i in 1:5) {
  print( starwars$name[i])
}
[1] "Luke Skywalker"
[1] "C-3PO"
[1] "R2-D2"
[1] "Darth Vader"
[1] "Leia Organa"
代码
starwars$name[35]
[1] "Jar Jar Binks"
代码
for (i in 1:5) {
  cat("The height of", starwars$name[i], "is", starwars$height[i],"cm. \n")
}
The height of Luke Skywalker is 172 cm. 
The height of C-3PO is 167 cm. 
The height of R2-D2 is 96 cm. 
The height of Darth Vader is 202 cm. 
The height of Leia Organa is 150 cm. 
代码
for (i in 1:length(starwars$height)) {
  cat("The height of", starwars$name[i], "is", starwars$height[i],"cm. \n")
}
The height of Luke Skywalker is 172 cm. 
The height of C-3PO is 167 cm. 
The height of R2-D2 is 96 cm. 
The height of Darth Vader is 202 cm. 
The height of Leia Organa is 150 cm. 
The height of Owen Lars is 178 cm. 
The height of Beru Whitesun Lars is 165 cm. 
The height of R5-D4 is 97 cm. 
The height of Biggs Darklighter is 183 cm. 
The height of Obi-Wan Kenobi is 182 cm. 
The height of Anakin Skywalker is 188 cm. 
The height of Wilhuff Tarkin is 180 cm. 
The height of Chewbacca is 228 cm. 
The height of Han Solo is 180 cm. 
The height of Greedo is 173 cm. 
The height of Jabba Desilijic Tiure is 175 cm. 
The height of Wedge Antilles is 170 cm. 
The height of Jek Tono Porkins is 180 cm. 
The height of Yoda is 66 cm. 
The height of Palpatine is 170 cm. 
The height of Boba Fett is 183 cm. 
The height of IG-88 is 200 cm. 
The height of Bossk is 190 cm. 
The height of Lando Calrissian is 177 cm. 
The height of Lobot is 175 cm. 
The height of Ackbar is 180 cm. 
The height of Mon Mothma is 150 cm. 
The height of Arvel Crynyd is NA cm. 
The height of Wicket Systri Warrick is 88 cm. 
The height of Nien Nunb is 160 cm. 
The height of Qui-Gon Jinn is 193 cm. 
The height of Nute Gunray is 191 cm. 
The height of Finis Valorum is 170 cm. 
The height of Padmé Amidala is 185 cm. 
The height of Jar Jar Binks is 196 cm. 
The height of Roos Tarpals is 224 cm. 
The height of Rugor Nass is 206 cm. 
The height of Ric Olié is 183 cm. 
The height of Watto is 137 cm. 
The height of Sebulba is 112 cm. 
The height of Quarsh Panaka is 183 cm. 
The height of Shmi Skywalker is 163 cm. 
The height of Darth Maul is 175 cm. 
The height of Bib Fortuna is 180 cm. 
The height of Ayla Secura is 178 cm. 
The height of Ratts Tyerel is 79 cm. 
The height of Dud Bolt is 94 cm. 
The height of Gasgano is 122 cm. 
The height of Ben Quadinaros is 163 cm. 
The height of Mace Windu is 188 cm. 
The height of Ki-Adi-Mundi is 198 cm. 
The height of Kit Fisto is 196 cm. 
The height of Eeth Koth is 171 cm. 
The height of Adi Gallia is 184 cm. 
The height of Saesee Tiin is 188 cm. 
The height of Yarael Poof is 264 cm. 
The height of Plo Koon is 188 cm. 
The height of Mas Amedda is 196 cm. 
The height of Gregar Typho is 185 cm. 
The height of Cordé is 157 cm. 
The height of Cliegg Lars is 183 cm. 
The height of Poggle the Lesser is 183 cm. 
The height of Luminara Unduli is 170 cm. 
The height of Barriss Offee is 166 cm. 
The height of Dormé is 165 cm. 
The height of Dooku is 193 cm. 
The height of Bail Prestor Organa is 191 cm. 
The height of Jango Fett is 183 cm. 
The height of Zam Wesell is 168 cm. 
The height of Dexter Jettster is 198 cm. 
The height of Lama Su is 229 cm. 
The height of Taun We is 213 cm. 
The height of Jocasta Nu is 167 cm. 
The height of R4-P17 is 96 cm. 
The height of Wat Tambor is 193 cm. 
The height of San Hill is 191 cm. 
The height of Shaak Ti is 178 cm. 
The height of Grievous is 216 cm. 
The height of Tarfful is 234 cm. 
The height of Raymus Antilles is 188 cm. 
The height of Sly Moore is 178 cm. 
The height of Tion Medon is 206 cm. 
The height of Finn is NA cm. 
The height of Rey is NA cm. 
The height of Poe Dameron is NA cm. 
The height of BB8 is NA cm. 
The height of Captain Phasma is NA cm. 
代码
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
代码
#create a break
for (i in starwars$name) {
  print(i)
  if (i == "Darth Vader") {
    break
  }
}
[1] "Luke Skywalker"
[1] "C-3PO"
[1] "R2-D2"
[1] "Darth Vader"
代码
#skip
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
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. 
回到顶部