中位数替换,需要数值数据

Median replace, needs numeric data

我正在尝试根据一组来估算缺失值。我收到一个错误消息,指出 median() 函数需要数字数据,但我的所有数据都是数字,所以我看不到这个问题。这是一个可重现性最低的示例。

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 in median.default(x, na.rm = TRUE) : need numeric data

这段代码可以正常工作,所以问题出在中值函数上。

df_fixed = by(df,df$cluster,function(x){replace(x,is.na(x),1)})
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