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:

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:

 

 

Additionally, you may have a look at the other tutorials of this homepage.

 

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.

 

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.


2 Comments. Leave new

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.

Top