In R, how do I create a long frequency table for every unique combination of the other columns

28 Views Asked by At

Here are the first few rows of my table...

enter image description here

In R, how do I create a long table where Col A and Col B show every possible combination and Col C contains either a or b (or c or d or whatever its value might be), and Col D shows the frequency of Col C value for each combination of Col A and B.

Using the example above, the results should look like this (showing just the first few rows)...

enter image description here

I tried combinations of melt() and table() with little success.

1

There are 1 best solutions below

0
r2evans On
as.data.frame.table(xtabs(~ ColA + ColB + ColC, dat))
#   ColA ColB ColC Freq
# 1    1    1    a    2
# 2    2    1    a    0
# 3    1    2    a    1
# 4    2    2    a    0
# 5    1    1    b    1
# 6    2    1    b    2
# 7    1    2    b    1
# 8    2    2    b    1

Data

dat <- structure(list(ColA = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L), ColB = c(1L, 1L, 1L, 2L, 2L, 1L, 1L, 2L), ColC = c("a", "a", "b", "b", "a", "b", "b", "b")), class = "data.frame", row.names = c(NA, -8L))