Handling is.na()
is.na checks each value for being missing, like looking for empty seats in a classroom. You can use it to find or skip the blanks in your data.
In this page:
Syntax
is.na(x)
x[!is.na(x)]
mean(x, na.rm = TRUE)
Handling is.na()
is.na(x) tests each element of a vector for missing values (NA), returning a logical vector.
It's essential for cleaning data before analysis, since many functions either propagate NA or need na.rm = TRUE to ignore it. sum(is.na(x)) is a common idiom for counting how many missing values a vector contains.
Warning:
- Never compare directly with x == NA to test for missing values -- it always returns NA, not TRUE/FALSE.
- Use is.na(x) instead.
Example: Handling is.na()
values <- c(10, NA, 25, NA, 30)
print(is.na(values))
cat("Number of missing values:", sum(is.na(values)), "\n")
clean_values <- values[!is.na(values)]
print(clean_values)
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Testing for missing values with
x == NA, which always givesNA; useis.na(x). - Forgetting that
NaNcounts asNAinis.na(), butNAis notNaN. - Removing
NAwith!is.na()and forgetting to save the result, since the original stays unchanged.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: