library(plyr)
df
id channel
1 1 a
2 1 b
3 1 c
4 2 a
5 2 c
6 3 a
tb <- table(ddply(df, .(id), function(x) {x$id <- x$channel; expand.grid(x)}))
tb
channel
id a b c
a 3 1 2
b 1 1 1
c 2 1 2
names(dimnames(tb)) <- NULL
tb
a b c
a 3 1 2
b 1 1 1
c 2 1 2
Now some explanations and something about matrix tables as output of table()
. There is an example in ?table
a <- letters[1:3]
(b <- sample(a))
[1] "b" "c" "a"
table(a, b)
b
a a b c
a 0 1 0
b 0 0 1
c 1 0 0
So it matches elements by the position.. Now if we have
id channel
1 a
1 b
1 c
2 a
...
Then sharing the same id
could be showed by splitting the data frame by id
, creating a copy of channel
column and getting all the combinations of these two columns:
tbl <- expand.grid(data.frame(x = c("a","b","c"), y = c("a", "b", "c")))
tbl
x y
1 a a
2 b a
3 c a
4 a b
5 b b
6 c b
7 a c
8 b c
9 c c
table(tbl$x, tbl$y)
a b c
a 1 1 1
b 1 1 1
c 1 1 1