Remove NA Values from Vector in R
Last Updated :
31 Aug, 2021
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
R
a= c (1,2, NA ,4,5, NA ,4,5,6, NA )
a
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
- na.rm is used to remove na
- if na.rm=TRUE it will not consider na
- if na.rm=FALSE it will consider na
Syntax:
mean(vector, na.rm = TRUE)
Syntax:
var(vector, na.rm = TRUE)
Example: R program to remove na by using sum, var, and mean
R
a= c (1,2, NA ,4,5, NA ,4,5,6, NA )
a
var (a, na.rm = TRUE )
sum (a, na.rm = TRUE )
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:
- Returns the non-NA values
- Returns the indexes of NA values which are removed from the vector
Note: Indexing starts with 1
Example: R program to consider a vector and remove NA values
R
a= c (1,2, NA ,4,5, NA ,4,5,6, NA )
print (a)
print ( "_______________________" )
a= na.omit (a)
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"
Share your thoughts in the comments
Please Login to comment...