R is.na
Use is.na to detect a missing character field in an imported record.
A simple example
is.na
- Start with No string supplied
- Do this Try to read its length
- Result No length available
Syntax
is.na(phone)
Run these examples in R
Save one example at a time as Lesson.R. Use R 4.x.
Rscript --vanilla Lesson.RPrint a label when the phone number is missing
A school prints contact cards from an enrollment form. Some families leave the optional phone field blank, so the printer needs a readable fallback before it measures or displays that field.
phone <- NA_character_
if (is.na(phone)) {
cat("Ask for a phone number\n")
} else {
cat(phone, "\n", sep = "")
}
Ask for a phone number
The missing contact follows the fallback branch, so the card still has a printable phone field.
Print an existing extension
A department saved its internal extension in the staff directory. Confirm that a contact value is available before printing it on a dispatch slip.
Flag an unfilled contact field
A delivery booking reaches reception without a contact value. Confirm that a contact value is available before printing it on a dispatch slip.
What to watch for
Comparing phone to NA with == produces a missing logical value. Use is.na for the test.