๐ŸŽ“ A1Learner
๐Ÿ”
0 of 40 lessons completed

R Missing Values

A missing value is a slot in a vector where no value was recorded. R writes a missing value as NA.

A gap in a vector

This vector holds two numbers and one missing slot. R prints the missing slot as NA.

print(c(1, 2, NA))

Testing for gaps

is.na checks each item in the vector. Only the missing slot comes back TRUE.

print(is.na(c(1, 2, NA)))

Skipping missing values

The first sum touches a gap and returns NA. With na.rm set to TRUE the sum and the mean skip the gaps.

v <- c(4, NA, 7, NA, 9)
print(sum(v))
print(sum(v, na.rm = TRUE))
print(mean(v, na.rm = TRUE))

Counting the gaps

is.na marks the three gaps in this vector. sum counts those marks into one number.

w <- c(3, NA, 5, NA, NA, 8)
print(sum(is.na(w)))

Nothing at all

NULL stands for nothing at all. Printing it shows the word NULL.

print(NULL)

Example

readings <- c(22, NA, 25, 21, NA)
print(sum(is.na(readings)))
print(sum(readings, na.rm = TRUE))
print(mean(readings, na.rm = TRUE))

Key points

  • NA can sit in a vector of any type.
  • is.na tests every item and returns TRUE for each missing slot.
  • A total that touches a missing value comes back as NA.
  • The argument na.rm = TRUE tells a function to skip missing values.
  • sum over the is.na result counts how many values are missing.
  • NULL stands for nothing at all and holds no value.
  • NaN is the result of a calculation that has no numeric answer.

In this example, two of the five readings are missing. The count of missing values comes from sum over the is.na result. The total and the average then skip the gaps.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท rdrr.io R Snippets

Exercise

What does sum(c(4, NA, 7)) print?