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.
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
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.
Statistics Globe Newsletter