Vectors are a commonly used data structure in R to store one-dimensional data of the same type. It can happen that the vectors have NA (or missing) values present and thus it’s handy to know how to remove such values. In this tutorial, we will look at how to remove NA values from a Vector in R with the help of some examples.
How to remove NA values from a Vector in R?
You can use the is.na()
function in R to check if each value in the vector is an NA value or not and then use the []
notation to remove the NA values from the vector. The following is the syntax –
# remove NA values from vector vec vec[!is.na(vec)]
We get a vector with the NA values removed from the original vector.
Examples
Let’s look at some examples of using the above syntax to remove NA values from a vector.
Remove NA values from a numeric vector
First, we will create a vector of numbers along with some NA values. Then, we will remove the missing values using the above method.
Highlighted programs for you
Flatiron School
Flatiron School
University of Maryland Global Campus
University of Maryland Global Campus
Creighton University
Creighton University
# create a vector vec <- c(1, 2, NA, 3, 4, NA, NA) # remove NA values from vector vec <- vec[!is.na(vec)] # display the vector print(vec)
Output:
[1] 1 2 3 4
You can see that the resulting vector does not have any NA values. Here, we used the is.na()
function to identify the missing values and then used the []
notation along with the !
operator to keep only the non-NA values in the vector.
Remove NA values from a character vector
Let’s look at another example. This time we will remove NA values from a vector of characters. The method remains the same – Identify which values are NA and which values are not NA using the is.na()
function and then use the []
notation to remove values that are not NA.
# create a vector vec <- c("a", NA, "b", "c", NA, "d") # remove NA values from vector vec <- vec[!is.na(vec)] # display the vector print(vec)
Output:
[1] "a" "b" "c" "d"
The resulting vector does not have any missing values.
You might also be interested in –
- Create a Vector in R – With Examples
- Check if an Element is present in an R Vector
- How to Print a Vector in R?
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.