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 summarise all factor levels with data.table?

Let’s see a minimal example:

library(data.table)
DT = data.table(x=factor(rep(c("b","a","c"),each=3)))
DT[x!="c"][, .N, by = x]
        x     N
   <fctr> <int>
1:      b     3
2:      a     3

In this example, as x is a factor with 3 levels a,b,c, I would like the output was

        x     N
   <fctr> <int>
1:      b     3
2:      a     3
3:      c     0

or having some argument to control this. Is there some way to get this output?

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

Thanks!

>Solution :

Using the join syntax

DT[x != "c"][levels(x), on = "x", .N, by = .EACHI]

#         x     N
#    <char> <int>
# 1:      a     3
# 2:      b     3
# 3:      c     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