I want to replace missing values in columns of a dataframe. I have written the following code
MedianImpute <- function(data=data)
{
for(i in 1:ncol(data))
{
if(class(data[,i]) %in% c("numeric","integer"))
{
if(sum(is.na(data[,i])))
{
data[is.na(data[,i]),i] <-
median(data[,i],na.rm = TRUE)
}
}
}
return(data)
}
This returns the dataframe with the NAs replaced by the column median. I do no want to use for loop, how can I get the same result using any of the apply functions in R?
You could use apply to apply a function across all columns
dat<-data.frame(c1=c(1,2,3,NA),c2=c(10, NA, 20, 30))
apply(dat, 2, function(x) ifelse(is.na(x), median(x, na.rm=T), x))
slightly faster
imputeMedianv3<-function(x) apply(x, 2, function(x){x[is.na(x)]<-median(x, na.rm=T); x})
I'm sure if what you're looking for is performance, someone will provide a data table solution (unfortunately I am not familiar with that package so can't do myself).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With