MFR MFR - 18 days ago 6
R Question

count the frequency, how to have zero frequencies?

I wish to know the frequencies that occurred 0. Is there any simple way for that?

mydf <-data.frame(v1= c("a","b","b","a","b"), v2 =c("l1", "l2","l1","l1","l2"))


I use this one to see the frequencies of
v1
and
v2


library(plyr)
count(mydf, c('v1','v2'))


It gives me the following outcome.

v1 v2 freq
1 a l1 2
2 b l1 1
3 b l2 2


I wish to have zeros in my output. For instance combination of
a
and
l2
never occurred. How can I have the following output?

v1 v2 freq
1 a l1 2
2 b l1 1
3 b l2 2
4 a l2 0

Answer
table(mydf$v1, mydf$v2)

    l1 l2
  a  2  0
  b  1  2

as.data.frame(table(mydf$v1, mydf$v2))
   Var1 Var2 Freq
1    a   l1    2
2    b   l1    1
3    a   l2    0
4    b   l2    2
Comments