【发布时间】:2015-05-02 16:05:43
【问题描述】:
我有以下功能:
miss.case = function(x){
y = apply(x, 1, is.na)
y = apply(y, 2, sum)
return(y)
}
miss.hist = function(df, percent=T) {
m = miss.case(df)
d = data.frame(number.of.NA = m)
max.miss = max(m)
min.miss = min(m)
if (percent) {
d$percent = (d$number.of.NA/sum(d$number.of.NA))*100
g = ggplot(data = d, aes(x = number.of.NA)) +
geom_bar(aes(y = ((..count..)/sum(..count..))*100)) +
scale_y_continuous('percent') +
xlab("Number of NAs") +
scale_x_discrete(breaks=min.miss:max.miss)
return(g)
}
else {
g = ggplot(data = d, aes(x = number.of.NA)) +
geom_histogram() +
xlab("Number of NAs") +
scale_x_discrete(breaks=min.miss:max.miss)
return(g)
}
}
使用 ggplot2 可以生成很好的缺失数据直方图。几乎。要查看,请尝试使用一些测试数据:
#make some test data
test.data = as.data.frame(iris)
set.seed(1)
which.remove = cbind(sample(1:150, 250, T),
sample(1:5, 250, T))
for (row in 1:nrow(which.remove)) {
test.data[which.remove[row,1],which.remove[row,2]] = NA
}
#plot missing
miss.hist(test.data)
这应该给你这个:
你明白什么是错的。情节的右侧是奇怪的空洞。现在你可能会想,这很容易通过设置限制来解决,即:limits=c(min.miss, max.miss)。但是不,这解决了问题,但消除了蜱虫!
改变它们的顺序并没有什么不同。如何解决这两个问题?
【问题讨论】:
-
我刚刚运行了整个脚本并得到了以下错误。
Error in miss.hist(test.data) : could not find function "miss.case"。我想知道您是否想仔细检查您的代码。 -
对不起,这是一个自定义函数:raw.githubusercontent.com/Deleetdk/psych2/master/psych2.R我会更新帖子。