Reputation: 411
I am trying to impute missing values based on a group. I am getting an error that the median() function requires numeric data, but all of my data is numeric so I can't see the issue. Here is a minimally reproducible example.
set.seed(123)
cluster = sample(seq(1,10),1000,replace=TRUE)
V1 = sample(c(runif(100),NA),1000,replace=TRUE)
V2 = sample(c(runif(100),NA),1000,replace=TRUE)
df = as.data.frame(cbind(cluster,V1,V2))
df_fixed = by(df,df$cluster,function(x){replace(x,is.na(x),median(x, na.rm=TRUE))})
Error returned:
Error in median.default(x, na.rm = TRUE) : need numeric data
This code will work though, so the issue is with the median function.
df_fixed = by(df,df$cluster,function(x){replace(x,is.na(x),1)})
Upvotes: 0
Views: 1032
Reputation: 24252
df_fixed <- apply(df[,2:3], 2, function(x) {
md <- sapply(sort(unique(df$cluster)), function(k) median(x[df$cluster==k], na.rm=TRUE))
x[is.na(x)] <- md[df$cluster][is.na(x)]
return(x)
})
any(is.na(df_fixed))
# [1] FALSE
Upvotes: 1