Open In App

Remove NA Values from Vector in R

In this article, we are going to discuss how to remove NA values from the vector.

Method 1: Using is.na()

We can remove those NA values from the vector by using is.na(). is.na() is used to get the na values based on the vector index. !is.na() will get the values except na.



Syntax:

vector[!is.na(vector)]



where the vector is the input vector

Example: R program to remove NA values using above method




# create a vector
a=c(1,2,NA,4,5,NA,4,5,6,NA)
 
# display a
a
 
# remove NA
a[!is.na(a)]

Output:

[1]  1  2 NA  4  5 NA  4  5  6 NA

[1] 1 2 4 5 4 5 6

Method 2: Using na.rm

we can also remove na values by computing the sum, mean, variance.

Syntax:

sum(vector, na.rm = TRUE)

where 

Syntax:

mean(vector, na.rm = TRUE)

Syntax:

var(vector, na.rm = TRUE)

Example: R program to remove na by using sum, var, and mean




# create a vector
a=c(1,2,NA,4,5,NA,4,5,6,NA)
 
# display a
a
 
# remove NA by computing variance
var(a, na.rm = TRUE)
 
# remove NA by computing sum
sum(a, na.rm = TRUE)
 
# remove NA by computing mean
mean(a, na.rm = TRUE)

Output:

[1]  1  2 NA  4  5 NA  4  5  6 NA
[1] 3.142857
[1] 27
[1] 3.857143

Method 3 : Using omit() method

omit() method is used to remove the NA values directly by resulting in the non-NA values and omitted NA values indexes.

Syntax: 

na.omit(vector)

where the vector is the input vector

Return type:

Note: Indexing starts with 1

Example: R program to consider a vector and remove NA values




# create a vector with integers along with NA
a=c(1,2,NA,4,5,NA,4,5,6,NA)
 
# display
print(a)
 
print("_______________________")
 
# remove NA using omit() function
a=na.omit(a)
 
# display vector
print(a)

Output:

[1]  1  2 NA  4  5 NA  4  5  6 NA
[1] "_______________________"
[1] 1 2 4 5 4 5 6
attr(,"na.action")
[1]  3  6 10
attr(,"class")
[1] "omit"

Article Tags :