O'Reilly logo

R Data Analysis Cookbook - Second Edition by Kuntal Ganguly

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Treating the outliers with mean/median imputation

We can handle outliers with mean or median imputation by replacing the observations lower than the 5th percentile with mean and those higher than 95th percentile with median. We can use the same statistics, mean or median, to impute outliers in both directions:

> impute_outliers <- function(x,removeNA = TRUE){    quantiles <- quantile( x, c(.05, .95 ),na.rm = removeNA )    x[ x < quantiles[1] ] <- mean(x,na.rm = removeNA )    x[ x > quantiles[2] ] <- median(x,na.rm = removeNA )    x}> imputed_data <- impute_outliers(ozoneData$pressure_height)

Validate the imputed data through visualization:

> par(mfrow = c(1, 2))> boxplot(ozoneData$pressure_height, main="Pressure Height having Outliers", boxwex=0.3)

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required