Replace NA with Last Observed Value in R (Example)
In this R tutorial you’ll learn how to replace NAs with the previous non-NA value.
Table of contents:
- Creation of Example Data
- Example: Replace NA with latest non-NA Value in R
- Video, Further Resources & Summary
Let’s dive into it.
Creation of Example Data
For the example of this tutorial, we will use a very simple numeric vector:
x <- c(1, 2, NA, NA, NA, 3, NA, 4) # Create example data x # Print example data # 1 2 NA NA NA 3 NA 4
As you can see based on the previous R code, our example vector contains values ranging from 1 to 4 with NA values in between.
Example: Replace NA with latest non-NA Value in R
Let’s assume that we want to replace these NA values with the latest observed value in our data vector. We can do that based on the zoo add-on package. Let’s install and load the package to RStudio:
install.packages("zoo") # Install zoo package library("zoo") # Load zoo package
The zoo R package contains the na.locf function, which is a generic function for replacing each NA with the most recent non-NA value prior to it. Let’s do this in practice:
na.locf(x) # Apply na.locf function # 1 2 2 2 2 3 3 4
Based on the previous output of the RStudio console you can see that all NA values were replaced with the previously observed number.
Video, Further Resources & Summary
I have recently published a video on my YouTube channel, which explains the R programming codes of this article. You can find the video below:
Besides that, you might want to have a look at the related articles on my website. Please find a selection of interesting articles here:
- Replace NA with 0
- coalesce Function of dplyr Package
- R is.na Function
- R na_if Function of dplyr Package
- What are NA Values?
- Remove NA Values from Vector in R
- R Functions List (+ Examples)
- The R Programming Language
In summary: In this R tutorial you learned how to fill missing values using the previous observation. In case you have further questions, let me know in the comments section below.
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.







2 Comments. Leave new
It fixed all my problem, thanks a lot!!!
This is great to hear Emilio. Thanks for the comment! 🙂