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 # [1] NA NA NA "x" NA "y"
Have a look at the previous output of the RStudio console. It shows that our example data is a vector with six vector elements. Some of these vector elements are missing (i.e. Not Available or NA).
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.
For this, we can use a combination of the which and is.na function as shown below:
which(!is.na(vec))[1] # Return first non-NA index # [1] 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.
Subscribe to the Statistics Globe Newsletter
Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.
Thank you!
Welcome to the Statistics Globe newsletter. From now on, I’ll send you regular emails about statistics, data science, AI, and programming with R and Python.
I’m Joachim Schork. On this website, I provide statistics tutorials as well as code in Python and R programming.
Statistics Globe Newsletter
Get regular updates on the latest tutorials, offers & news at Statistics Globe. I hate spam & you may opt out anytime: Privacy Policy.
Thank you!
Please check your email inbox and click the confirmation link to complete your subscription. If you don’t see the email within a few minutes, please also check your spam/junk folder.






