dplyr top_n总结删除0

时间:2016-02-08 13:11:25

标签: r dplyr top-n

如何在使用top_n和dplyr时删除表摘要中的0?

library(ggplot2)
library(dplyr)
data("diamonds")
diamonds #set diamonds as data.frame

manualTest = diamonds %>%
  count(cut)  %>%
  top_n(3)


table(manualTest$cut)

结果

 Fair      Good Very Good   Premium     Ideal 
    0         0         1         1         1 

预期结果

 Very Good   Premium     Ideal 
  1         1         1 

1 个答案:

答案 0 :(得分:0)

如果您执行str(manualTest),则会看到manualTest$cutfactor变量。所以解决方案就是让它成为一个角色。三个选项

1)
manualTest = diamonds %>%
count(cut)  %>% mutate(cut = as.character(cut)) %>% 
top_n(3)
2)
manualTest$cut <- as.character(manualTest$cut)

然后运行table(manualTest$cut)

3)
table(as.character(manualTest$cut))