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)
ListenData Logo
Spread the Word!
Share
Related Posts
About Author:
Deepanshu Bhalla

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
Looks like you are using an ad blocker!

To continue reading you need to turnoff adblocker and refresh the page. We rely on advertising to help fund our site. Please whitelist us if you enjoy our content.