How to Remove NA Values from Vector in R?(3 Methods)

Removing NA values from a vector in R can be achieved using one of three methods: calling the na.omit() function to remove entire observations containing NA values, using the is.na() function and indexing to subset a vector without NA values, or using the na.exclude() function to return a vector with NA values excluded.


You can use one of the following methods to remove NA values from a vector in R:

Method 1: Remove NA Values from Vector

data <- data[!is.na(data)]

Method 2: Remove NA Values When Performing Calculation Using na.rm

max(data, na.rm=T)
mean(data, na.rm=T)
...

Method 3: Remove NA Values When Performing Calculation Using na.omit

max(na.omit(data))
mean(na.omit(data))
...

The following example shows how to use each of these methods in practice.

Method 1: Remove NA Values from Vector

The following code shows how to remove NA values from a vector in R:

#create vector with some NA values
data <- c(1, 4, NA, 5, NA, 7, 14, 19)

#remove NA values from vector
data <- data[!is.na(data)]

#view updated vector
data

[1]  1  4  5  7 14 19

Notice that each of the NA values in the original vector have been removed.

Method 2: Remove NA Values When Performing Calculation Using na.rm

The following code shows how to use the na.rm argument to remove NA values from a vector when performing some calculation:

#create vector with some NA values
data <- c(1, 4, NA, 5, NA, 7, 14, 19)

#calculate max value and remove NA values
max(data, na.rm=T)

[1] 19

#calculate mean and remove NA values
mean(data, na.rm=T)

[1] 8.333333

#calculate median and remove NA values
median(data, na.rm=T)

[1] 6

Method 3: Remove NA Values When Performing Calculation Using na.omit

The following code shows how to use the na.omit argument to omit NA values from a vector when performing some calculation:

#create vector with some NA values
data <- c(1, 4, NA, 5, NA, 7, 14, 19)

#calculate max value and omit NA values
max(na.omit(data))

[1] 19

#calculate mean and omit NA values
mean(na.omit(data))

[1] 8.333333

#calculate median and omit NA values
median(na.omit(data))

[1] 6

The following tutorials explain how to perform other common operations with missing values in R:

x