Skip to content

Instantly share code, notes, and snippets.

@AVJdataminer
Created July 27, 2017 23:58
Show Gist options
  • Save AVJdataminer/3f41f8e4e49b9406affb0b40760d0f39 to your computer and use it in GitHub Desktop.
Save AVJdataminer/3f41f8e4e49b9406affb0b40760d0f39 to your computer and use it in GitHub Desktop.
Fill NA's in R
Fill_NA<-function(x,home,modelpath){
setwd(modelpath)
if(nrow(x)<1){x<-read.csv(list.files(pattern = "indata_file.csv"))}
#split into numeric and non-numeric
require(PCAmixdata)
ds=splitmix(x)
impute.med <- function(x) {
z <- median(x, na.rm = TRUE)
x[is.na(x)] <- z
return(x)
}
#treat numeric NA's
dat2 <- data.frame(sapply(ds$X.quanti, function(x){
if(is.numeric(x) & any(is.na(x))){
impute.med(x)
} else {
x
}
}
))
#treat factor or character Na's
df1=lapply(ds$X.quali,fct_explicit_na)
#paste two df's back together
out1=cbind(dat2,df1)
#write.csv(out1, "Na_filled.csv", row.names = F)
return(out1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment