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

Imputing random values sampled from non-missing values

If you want to impute random values sampled from the non-missing values of the variable, you can use the following two functions:

rand.impute <- function(a) {   missing <- is.na(a)   n.missing <- sum(missing)   a.obs <- a[!missing]   imputed <- a   imputed[missing] <- sample (a.obs, n.missing, replace=TRUE)   return (imputed) }  random.impute.data.frame <- function(dat, cols) {   nms <- names(dat)   for(col in cols) {     name <- paste(nms[col],".imputed", sep = "")     dat[name] <- rand.impute(dat[,col])   }   dat } 

With these two functions in place, you can use the following to impute random values for both Income and Phone_type:

> dat <- read.csv("missing-data.csv", na.strings="") > random.impute.data.frame(dat, ...

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