Find Index Position of First Non-NA Value in R (Example)
This post explains how to get the position of the first non-NA value in a vector in R.
Table of contents:
You’re here for the answer, so let’s get straight to the example:
Construction of Example Data
The first step is to define some data that we can use in the example code below:
vec <- c(NA, NA, NA, "x", NA, "y") # Create example vector vec # Print example vector #  NA NA NA "x" NA "y"
Example: Return Index of First Non-NA Value Using which() & is.na() Functions
The following R syntax illustrates how to identify the index location of the very first vector element that is not NA.
which(!is.na(vec)) # Return first non-NA index #  4
As you can see, the RStudio console has returned the value 4, i.e. the first non-NA value is at the fourth index position of our example vector.
Video & Further Resources
Some time ago I have released a video on my YouTube channel, which explains the R programming code of this post. You can find the video below.
In addition, you could have a look at some of the related tutorials of my homepage. I have published several articles on topics such as data inspection, vectors, and extracting data.
- Extract data.table Column as Vector Using Index Position
- Get Value of Data Element without Name or Index
- Find Index of Maximum & Minimum Value of Vector & Data Frame Row
- Add New Row at Specific Index Position to Data Frame
- Introduction to R
To summarize: In this R tutorial you have learned how to find the first vector element that is not NA.
Please note that we have used a vector object as input for this example. However, we could apply the same R code to the column of a data frame to get the first non-NA row value.
Tell me about it in the comments, in case you have any further questions.