Get startedGet started for free

Removing NAs

We previously computed the average of na_example using mean(na_example) and obtain NA. This is because the function mean returns NA if it encounters at least one NA. A common operation is therefore removing the entries that are NA and after that perform operations on the rest.

This exercise is part of the course

Data Science R Basics

View Course

Exercise instructions

Write one line of code to compute the average, but only for the entries that are not NA making use of the ! operator before ind. (Remember that you can use help("!") to find out more about what ! does.)

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Note what we can do with the ! operator
x <- c(1, 2, 3)
ind <- c(FALSE, TRUE, FALSE)
x[!ind]

# Create the ind vector
library(dslabs)
data(na_example)
ind <- is.na(na_example)

# We saw that this gives an NA
mean(na_example)

# Compute the average, for entries of na_example that are not NA 
Edit and Run Code