remove NA values from a list in R

R – Remove NA Values From a List

Missing values in R are represented by NA. When working with lists in R, it can be handy to know how to handle and remove such values from the list. In this tutorial, we will look at how to remove NA values from a list in R with the help of some examples.

How to remove NA values from a list in R?

You can use the is.na() function to identify and remove the NA values from a list in R. Use the !is.na() expression to identify the non-NA values in the list and then use the resulting logical index to filter out the NA values. The following is the syntax –

# remove NA values from list
ls <- ls[!na.rm(ls)]

It returns a new list with the NA values removed.

Examples

Let’s now look at some examples of using the above method to remove NA values from a list.

Remove NA values from a list

First, let’s create a list of some numbers along with some NA values. Then, we will remove the missing values (NA values) using the syntax from above.

# create a list
ls <- list(1, 2, NA, 3, 4, NA, NA)
# remove NA values from ls
ls <- ls[!is.na(ls)]
# display the list
print(ls)

Output:

[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3

[[4]]
[1] 4

The resulting list does not have any NA values. Here, we use the expression !is.na(ls) to identify the non-NA values in the list. We then use the result from this expression as a logical index to filter the list and thus we get the list with the NA values removed.

Let’s now look at another example. This time we’ll create a list with no NA values and apply the same method.

📚 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 list
ls <- list(1, 2, 3, 4)
# remove NA values from ls
ls <- ls[!is.na(ls)]
# display the list
print(ls)

Output:

[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3

[[4]]
[1] 4

You can see that we get the original list as the output since there were no NA values to remove in this list.

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.


Author

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

Scroll to Top