This seems simple enough but I could not find an easy answer anywhere.
If we have the following data and use table():
df <- data.frame(x=c("a","b","a"),y=c("b","a","c"))
table(df)
y
x a b c
a 0 1 1
b 1 0 0
whats the easiest way to get:
y
x a b c
a 0 1 1
b 1 0 0
C 0 0 0
without adding the c row manually after.
Here is one way. Essentially, you need to make sure that
xandyboth have the same levels. I do that by computing theunion()of their respectivelevels()and thentransform()the originalxandyto both have this common set of levels:Your example has an easy solution – just give
xthe same levels asy, as the levels ofyare complete. In more general situations where neitherxnoryhas a complete set of levels, the code I show will get that complete set for you and thus works in both situations.