R — Skipping iterations with next
In R, next skips the remainder of a loop iteration. An explicit missing-value check makes the guard work even when a numeric vector includes NA.
A simple example
Skip just the number 2
- Start with Visit 1 through 3
- Do this Skip 2
- Result 1 → 3
for (n in 1:3) {
if (n == 2) next
cat(n, "\n", sep = "")
}
1 3
Exclude invalid readings while keeping zero
Skip negative readings, which represent invalid measurements here. Count every valid reading, including zero, and add it to the total. Short-circuit || checks is.na first. It prevents the unknown comparison NA < 0 from becoming the condition of an if statement.
A counter records visitors in each time interval. A negative reading signals a fault, while zero means the counter worked and nobody entered. Keeping 0, 4 and 6 gives three valid intervals and ten visitors.
Run the example
Use R 4.x. Run these commands from the directory containing the example.
Rscript --vanilla Lesson.R
count <- 0L
total <- 0L
for (reading in c(-2L, 0L, 4L, NA_integer_, -1L, 6L)) {
if (is.na(reading) || reading < 0L) next
count <- count + 1L
total <- total + reading
}
cat(sprintf("%d readings, sum %d\n", count, total))
3 readings, sum 10
The valid values are 0, 4, and 6. Skipping the negative entries changes the count without losing the measured zero.
Try it yourself
Append −3 and then 0. What should the count and sum become?
Check your answer
The count rises to 4 and the sum stays 10. Only the appended zero is a valid measurement.