当NA值无效时如何处理NA值?

时间:2016-01-11 21:09:36

标签: r ggplot2

我有一个方便的功能来计算观察次数和相对比例。它工作正常,但有时当我阅读Excel电子表格时,我得到了" NA"值仅为空单元格,如"",导致R无法识别为NA值,如下面的输出所示。这对于生成图表不是很有趣。

> table(is.na(factor(BASE$Q008)))

FALSE 
  437 

> df
Source: local data frame [6 x 3]

            Q008     n  prop
          (fctr) (int) (dbl)
1     Evangelical  172  0.39
2       Catholic   150  0.34
3         Other     51  0.12
4  Not religious    57  0.13
5    Protestant      6  0.01
6                    1  0.00 

为了绕过这个,我需要用recode(BASE$Q008, from="", to=NA)重新编码因子。这给出了正确的测试,但即使在ggplot2中使用x=factor(Q008),也会在图表中绘制类别NA。

> table(is.na(as.character(BASE$Q008)))

FALSE  TRUE 
  436     1 

> df
Source: local data frame [6 x 3]

            Q008     n  prop
          (fctr) (int) (dbl)
1     Evangelical  172  0.39
2       Catholic   150  0.34
3         Other     51  0.12
4  Not religious    57  0.13
5    Protestant      6  0.01
6           NA       1  0.00 

是否有更好的方法来改进此代码段,以便在它们看起来什么都没有时识别NA值?另外,不将它们绘制为一个级别?

mytable <- function(x, ...) x %>% 
group_by_(...) %>% 
summarise(n = n()) %>% 
mutate(prop = round(n/sum(n),2))

0 个答案:

没有答案