← Back to R Course | Chapter 12: Best Practices | Lesson 4 of 6

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:

  1. Handling is.na()
Syntax
r
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()

markup
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)
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
  1. Testing for missing values with x == NA, which always gives NA; use is.na(x).
  2. Forgetting that NaN counts as NA in is.na(), but NA is not NaN.
  3. Removing NA with !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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.