Find Index Position of First Non-NA Value in vector in R
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.
 "Original Vector"  NA NA 2 NA 5 7  "First non-na index"  3
In case the vector doesn’t contain any non-missing values, then this approach throws an exception and returns Inf
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 :
 "Original Vector"  NA 1 3 NA 2 NA 5 7  "First non-na index"  2