Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to show missing factor level frequencies?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

.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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading