15

I need to remove the rows from the table function output, which have 0 counts in all the columns. 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
rawr
  • 20,481
  • 4
  • 44
  • 78
michalrudko
  • 1,432
  • 2
  • 16
  • 30
  • Can you show us what `ds` would look like for an animal which has no gender entries? – Tim Biegeleisen Apr 15 '15 at 00:41
  • 2
    Look at the `exclude=` parameter for `table()`. If you need more help, make a proper [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input data. – MrFlick Apr 15 '15 at 00:41

2 Answers2

19

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$animal <- droplevels(ds$animal)
with(ds, table(animal,gender))

here I used with because it prints headers.

pdb
  • 1,574
  • 12
  • 26
0

I came over this answer that is helpful even 7 years later, and I asked myself, if this works with tidyverse as well. 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.

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