Part 10 Missing values
NA (Not Available) is a recognized element in R.
- Finding missing values in a vector
# Create vector
<- c(4, 2, 7, NA)
x
# Find missing values in vector:
is.na(x)
# Remove missing values
na.omit(x)
!is.na(x) ] x[
- Some functions can deal with NAs, either by default, or with specific arguments:
<- c(4, 2, 7, NA)
x
# default arguments
mean(x)
# set na.rm=TRUE
mean(x, na.rm=TRUE)
- In a matrix or a data frame, keep only rows where there are no NA values:
# Create matrix with some NA values
<- matrix(c(1:10, NA, 12:2, NA, 15:20, NA), ncol=3)
mydata
# Keep only rows without NAs
complete.cases(mydata), ]
mydata[# or
na.omit(mydata)
Check this R blogger post on missing/null values