Chapter 21 Exemples avec des instructions modifiées
Nous pouvons imprimer les concentrations de \(\text{CO}_{2}\) pour les traitements chilled et compter le nombre de réplications en utilisant next
.
<- 0
count
for (i in 1:nrow(CO2)) {
if (CO2$Treatment[i] == "nonchilled")
next
# Skip to next iteration if treatment is nonchilled
<- count + 1
count # print(CO2$conc[i]) # You can turn this on if you want
# to
}print(count) # The count and print command were performed 42 times.
## [1] 42
sum(CO2$Treatment == "chilled")
## [1] 42
Nous aurions également pu écrire l’exemple ci-dessus en utilisant repeat
et break
:
<- 0
count <- 0
i repeat {
<- i + 1
i if (CO2$Treatment[i] == "nonchilled")
next # skip this loop
<- count + 1
count print(CO2$conc[i])
if (i == nrow(CO2))
break # stop looping
}
## [1] 95
## [1] 175
## [1] 250
## [1] 350
## [1] 500
## [1] 675
## [1] 1000
## [1] 95
## [1] 175
## [1] 250
## [1] 350
## [1] 500
## [1] 675
## [1] 1000
## [1] 95
## [1] 175
## [1] 250
## [1] 350
## [1] 500
## [1] 675
## [1] 1000
## [1] 95
## [1] 175
## [1] 250
## [1] 350
## [1] 500
## [1] 675
## [1] 1000
## [1] 95
## [1] 175
## [1] 250
## [1] 350
## [1] 500
## [1] 675
## [1] 1000
## [1] 95
## [1] 175
## [1] 250
## [1] 350
## [1] 500
## [1] 675
## [1] 1000
print(count)
## [1] 42
Enfin, on aurait pu aussi faire cela en utilisant une boucle while
:
<- 0
i <- 0
count while (i < nrow(CO2)) {
<- i + 1
i if (CO2$Treatment[i] == "nonchilled")
next # skip this loop
<- count + 1
count print(CO2$conc[i])
}
## [1] 95
## [1] 175
## [1] 250
## [1] 350
## [1] 500
## [1] 675
## [1] 1000
## [1] 95
## [1] 175
## [1] 250
## [1] 350
## [1] 500
## [1] 675
## [1] 1000
## [1] 95
## [1] 175
## [1] 250
## [1] 350
## [1] 500
## [1] 675
## [1] 1000
## [1] 95
## [1] 175
## [1] 250
## [1] 350
## [1] 500
## [1] 675
## [1] 1000
## [1] 95
## [1] 175
## [1] 250
## [1] 350
## [1] 500
## [1] 675
## [1] 1000
## [1] 95
## [1] 175
## [1] 250
## [1] 350
## [1] 500
## [1] 675
## [1] 1000
print(count)
## [1] 42