R Function : Imputing Missing Values

The following is the R code for replacing missing values with mean, median, zero.

########################################################
# Imputing Missing Values with Mean / Median / Zero
#########################################################

#Replacing NA with zero
mydata[is.na(mydata)] <- 0

#Function: Imputing Missing Values with mean/median/min
impute <- function(data, type) {
  for (i in which(sapply(data, is.numeric))) {
    data[is.na(data[, i]), i] <- type(data[, i],  na.rm = TRUE)
  }
  return(data)}

#Implementing Imputation Function (Mean/Median/Min)
newdata <- impute(mydata,median)
Related Posts
About Author:

Deepanshu founded ListenData with a simple objective - Make analytics easy to understand and follow. He has over 10 years of experience in data science. During his tenure, he has worked with global clients in various domains like Banking, Insurance, Private Equity, Telecom and Human Resource.

0 Response to "R Function : Imputing Missing Values"

Post a comment

Next → ← Prev
Love this Post? Spread the Word!
Share