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.

 

The YouTube video will be added soon.

 

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.

 

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.


Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top