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.
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
Alternatively, we could have written the example above using repeat and 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
Finally, one could have also done this using a while loop:
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