0Pricing
R Academy · Lesson

Removing and Replacing NA Values

Apply na.omit(), complete.cases(), and manual replacement strategies.

Strategies for Handling NA

There are three main strategies for handling missing values: remove them, replace them with a constant, or impute them using a statistical estimate. The right approach depends on your data and analysis goals.

data_vals <- c(88, NA, 72, NA, 91, 65, NA, 78)
cat('Original data:', data_vals, '
')
cat('NA count:', sum(is.na(data_vals)), '
')

# Strategy 1: remove
cat('After removal:', data_vals[!is.na(data_vals)], '
')
# Strategy 2: replace with 0
replaced <- data_vals; replaced[is.na(replaced)] <- 0
cat('Replaced with 0:', replaced, '
')

Removing NAs with x[!is.na(x)]

The most direct way to remove NAs from a vector is logical subsetting: x[!is.na(x)]. This keeps only the elements where is.na(x) is FALSE (i.e., present values).

response_times <- c(1.2, NA, 0.9, 1.5, NA, 1.1, 0.8, NA, 1.3)
cat('With NAs:    ', response_times, '
')
cat('Length:', length(response_times), '
')

clean_times <- response_times[!is.na(response_times)]
cat('Without NAs: ', clean_times, '
')
cat('Length:', length(clean_times), '
')
cat('Mean after removal:', round(mean(clean_times), 3), '
')

All lessons in this course

  1. Understanding NA in R
  2. Detecting and Counting Missing Values
  3. Removing and Replacing NA Values
  4. NA in Calculations and Aggregations
← Back to R Academy