Open In App

Find Index Position of First Non-NA Value in vector in R

Improve
Improve
Like Article
Like
Save
Share
Report

An atomic vector contains elements belonging to the same data type. It may also contain missing or NA values, at any index within the range of this vector. These NA values can be accessed in R using standard indexing methods. In this article, we are going to see how to find the Index Position of First Non-NA Value in vector in R Programming Language.

Method 1: Using is.na() and which() methods

The negation is.na() method is first applied over the atomic vector, which returns a boolean vector of the same length, where TRUE indicates that the value is non-na and FALSE indicates a missing or NA value. This is followed by the application of which() method which returns the indices of the non-na values. The aggregate function min() is then applied to get the first or the minimum elements out of all the indexes. 

Code:

R




# declaring a vector
vec <- c(NA, NA, 2, NA, 5, 7)
print ("Original Vector")
print (vec)
  
# getting indexes of all the non na elements
non_na_vec <- which(!is.na(vec))
  
# determining the minimum from these indices
first_non_na <- min(non_na_vec)
print ("First non-na index")
print (first_non_na)


Output:

[1] "Original Vector"
[1] NA NA  2 NA  5  7
[1] "First non-na index"
[1] 3

In case the vector doesn’t contain any non-missing values, then this approach throws an exception and returns Inf 

Warning message:

In min(non_na_vec) : no non-missing arguments to min; returning Inf

Method 2: which.max() method

which.max() method returns the first argument that is encountered within the vector with non-na value. The method has the following syntax in R : 

which.max(vec)

Code:

R




# declaring a vector
vec <- c(NA, 1, 3, NA, 2, NA, 5, 7)
print ("Original Vector")
print (vec)
  
# getting indexes of all the non na elements
non_na_vec <- which.max(!is.na(vec))
print ("First non-na index")
print (non_na_vec)


Output:

[1] "Original Vector"
[1] NA  1  3 NA  2 NA  5  7
[1] "First non-na index"
[1] 2


Last Updated : 16 May, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads