R Missing Values (NA)
Missing Values
In real data, some values are often missing. A person skipped a question in a survey, or a sensor was turned off for a day.
R marks a missing value with NA (Not Available):
Example
scores <- c(85, NA, 78)
scores
Try it Yourself »
Note that NA is written without quotes. "NA" with quotes is just a string.
Find Missing Values
Use the is.na() function to check which values are missing:
Example
scores <- c(85, NA, 78)
is.na(scores)
Try it Yourself »
You cannot use == to find NA values. R does not know what a missing value is, so it cannot know if it is equal to anything. The result is always NA:
Example
scores <- c(85, NA, 78)
scores == NA
Try it Yourself »
Use sum() together with is.na() to count the missing values:
Example
scores <- c(85, NA, 78, NA, 90)
sum(is.na(scores))
Try it Yourself »
Calculations with NA
If a vector has a missing value, functions like mean() and sum() return NA, because R cannot know the missing value.
Add na.rm = TRUE to skip the missing values (rm is short for remove):
Example
scores <- c(85, NA, 78)
mean(scores)
mean(scores, na.rm = TRUE)
sum(scores, na.rm = TRUE)
Try it Yourself »
Remove Missing Values
Use !is.na() inside the brackets to keep only the values that are not missing. The ! means "not":
Example
scores <- c(85, NA, 78, NA, 90)
scores[!is.na(scores)]
Try it Yourself »
Replace Missing Values
You can also replace all the missing values with another value, for example 0:
Example
scores <- c(85, NA, 78, NA, 90)
scores[is.na(scores)] <- 0
scores
Try it Yourself »
Missing Values in Data Frames
The na.omit() function removes every row that has a missing value:
Example
Data_Frame <- data.frame (
Name = c("Liam", "Jenny", "John"),
Age = c(25, NA, 31)
)
na.omit(Data_Frame)
Try it Yourself »
The row for Jenny is removed, because her Age is missing.
NA and NULL
R also has NULL, which is not the same as NA:
NAmeans that a value is missing. It still takes a place in a vector.NULLmeans nothing at all. It takes no place.
Example
length(NA)
length(NULL)
Try it Yourself »