R — Validating input and handling NA
R can use NA_integer_ for a missing integer result. Test it with is.na before comparing a proposed seat number with the allowed bounds.
A simple example
Turn text into a number
- Start with "2"
- Do this Read an integer, add 1
- Result 3
n <- as.integer("2")
if (!is.na(n)) cat(n + 1)
3
Validate a seat number
NA_integer_ preserves the return type while representing a missing result. Use is.na to test it. Conversion overflow can also produce NA, so check it before comparing the numeric range.
A minibus has seats numbered 1 to 8. A passenger entering 3 can be assigned that seat. Zero is numeric but outside the seating plan, and x cannot be read as a whole seat number.
Run the example
R 4. Run these commands from the directory containing the example.
Rscript Lesson.R
seat_number <- function(text) {
if (!grepl("^[0-9]+$", text)) return(NA_integer_)
value <- suppressWarnings(as.integer(text))
if (is.na(value) || value < 1L || value > 8L) return(NA_integer_)
value
}
for (text in c("3", "0", "x")) {
seat <- seat_number(text)
cat(if (is.na(seat)) "invalid" else seat, "\n", sep = "")
}
3 invalid invalid
Only whole-number seat labels from 1 through 8 are accepted. The text 3 passes both checks. Zero parses but is outside the range. The letter x does not represent a decimal seat number.
Try it yourself
Predict the results for 8, 9, and an empty string.
Check your answer
Only 8 is accepted. Nine is outside the range and an empty string has no digits. The existing loop can continue after either rejection.