Home > Enterprise >  How to show missing factor level frequencies?
How to show missing factor level frequencies?

Time:06-28

I'm trying to show missing values, but dplyr omits levels by default. I tried .drop = FALSE, but it didn't work.

mtcars %>% 
  group_by(cyl) %>% 
  count(vs)
cyl     vs      n
  4      0      1       
  4      1     10       
  6      0      3       
  6      1      4       
  8      0     14   

What I'd like to get is to add the factor level "1" of vs for factor level "8" of cyl and it be "0" for n. Like this:

cyl     vs      n
  4      0      1       
  4      1     10       
  6      0      3       
  6      1      4       
  8      0     14   
  8      1      0

See last line: 8 1 0

CodePudding user response:

.drop can work if the column is factor

library(dplyr)
mtcars %>% 
  count(cyl, vs = factor(vs, levels = 0:1), .drop = FALSE)

-output

  cyl vs  n
1   4  0  1
2   4  1 10
3   6  0  3
4   6  1  4
5   8  0 14
6   8  1  0
  • Related