remove NA values from a vector in R

R – Remove NA Values from a Vector

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.

# 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.

📚 Data Science Programs By Skill Level

Introductory

Intermediate ⭐⭐⭐

Advanced ⭐⭐⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

# 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 –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Authors

  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

  • Gottumukkala Sravan Kumar
Scroll to Top