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.

count <- 0

for (i in 1:nrow(CO2)) {
    if (CO2$Treatment[i] == "nonchilled")
        next
    # Skip to next iteration if treatment is nonchilled
    count <- count + 1
    # 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 :

count <- 0
i <- 0
repeat {
    i <- i + 1
    if (CO2$Treatment[i] == "nonchilled")
        next  # skip this loop
    count <- count + 1
    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 :

i <- 0
count <- 0
while (i < nrow(CO2)) {
    i <- i + 1
    if (CO2$Treatment[i] == "nonchilled")
        next  # skip this loop
    count <- count + 1
    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