Remove NA Values from Vector in R (2 Examples)
In this article you’ll learn how to remove NA values from a vector in the R programming language.
Table of contents:
- Creation of Example Data
- Example 1: Create New Vector without NA Values
- Example 2: Remove NA within Function via na.rm
- Video & Further Resources
With that, let’s do this:
Creation of Example Data
In the two examples of this R tutorial, I’ll use the following vector:
vec <- c(5, NA, 3, 9, NA, 4, NA) vec # 5 NA 3 9 NA 4 NA
As you can see based on the output of the RStudio console, our example vectors contains four numeric values and three NAs. Let’s remove these NAs…
Example 1: Create New Vector without NA Values
Example 1 shows how to create a new vector without any NA values in R. For this, we can use the is.na R function as follows:
vec_new <- vec[!is.na(vec)] vec_new # 5 3 9 4
The previous R code takes a subset of our original vector by retaining only values that are not NA, i.e. we extract all non-NA values.
Example 2: Remove NA within Function via na.rm
Another possibility is the removal of NA values within a function by using the na.rm argument. For instance, we could use the na.rm argument to compute the sum…
sum(vec, na.rm = TRUE) # 21
…the mean…
mean(vec, na.rm = TRUE) # 5.25
…or the variance of our vector:
var(vec, na.rm = TRUE) # 6.916667
Note: Even though most basic functions provide the na.rm argument, there are many function that do not provide such an option. If you want to perform more complex operations with your data, it is advisable to delete missing values in the forefront (as shown in Example 1).
Video & Further Resources
In case you need further explanations on the contents of this article, you may watch the following video of my YouTube channel. In the video, I explain the R syntax of this article in RStudio:
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.
Additionally, you may have a look at the other tutorials of this homepage.
- What are
Values? - The is.na Function
- NA Omit in R
- Remove Incomplete Rows
- Replace NA with 0
- R Functions List (+ Examples)
- The R Programming Language
Summary: You learned in this article how to delete vector elements that are NA in R. In case you have any further comments and/or questions, let me know in the comments.
Statistics Globe Newsletter