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 x and y both have the same levels. I do that by computing the union() of their respective levels() and then transform() the original x and y to both have this common set of levels:
> df <- data.frame(x=c("a","b","a"),y=c("b","a","c"))
> lev <- with(df, sort(union(levels(x), levels(y))))
> lev
[1] "a" "b" "c"
> df <- transform(df, x = factor(x, levels = lev), y = factor(y, levels = lev))
> table(df)
y
x a b c
a 0 1 1
b 1 0 0
c 0 0 0
Your example has an easy solution - just give x the same levels as y, as the levels of y are complete. In more general situations where neither x nor y has a complete set of levels, the code I show will get that complete set for you and thus works in both situations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With