简体   繁体   English

R表功能 - 如何删除0计数?

[英]R table function - how to remove 0 counts?

I need to remove the rows from the table function output, which have 0 counts in all the columns.我需要从表函数输出中删除行,这些行在所有列中都有 0 个计数。 Is there any easy way to do that?有什么简单的方法可以做到这一点吗?

table(ds$animal,ds$gender)

___ | M | F

Cat | 9 | 4 

Dog | 0 | 0

Rat | 4 | 3

I just would like to see those rows:我只想看看那些行:

___ | M | F

Cat | 9 | 4 

Rat | 4 | 3

you need to drop levels from the factor animal.你需要从因素动物中降低水平。

table(droplevels(ds$animal),ds$gender)

you can also just drop them from ds and then do the table您也可以将它们从 ds 中删除,然后执行表格

ds$animal <- droplevels(ds$animal)
with(ds, table(animal,gender))

here I used with because it prints headers.在这里我使用了,因为它打印标题。

I came over this answer that is helpful even 7 years later, and I asked myself, if this works with tidyverse as well. 7 年后,我得到了这个很有帮助的答案,我问自己,这是否也适用于 tidyverse。 It does, which I would like to share.确实如此,我想分享一下。

In this specific case, I wanted to remove a factor level before computing percentages.在这种特定情况下,我想在计算百分比之前删除一个因子水平。 And obviously, droplevels also works on the whole dataset.显然, droplevels也适用于整个数据集。

ds %>%
    filter(animal != "Dog") %>%
    select(animal, gender) %>%
    droplevels() %>%
    table() %>%
    prop.table(margin=2) %>%
    kable(digits = 2, caption="Percentage of Cats and Rats")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM