Chapter 20 Examples with modifying statements
We can print \(\text{CO}_{2}\) concentrations for chilled treatments and keep count of how many replications using 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
Alternatively, we could have written the example above using repeat
and 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
Finally, one could have also done this using a while
loop:
<- 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