Doesn't table
do what you want for your first question:
df$bin_index <- factor(df$bin_index, levels=1:5)
table(df[, c("Group", "bin_index")])
# bin_index
# Group 1 2 3 4 5
# 1 0 2 3 0 1
# 2 0 1 0 0 4
It shows the 0
entry for bin 3, group 2 (I presume that's what you meant, there are rows for bin 3 in group 1). Also, by setting the factor levels I was also able to get bin_index 1 to show up. For your second question, just use melt
:
library(reshape2)
melt(table(df[, c("Group", "bin_index")]))
# Group bin_index value
# 1 1 1 0
# 2 2 1 0
# 3 1 2 2
# 4 2 2 1
# 5 1 3 3
# 6 2 3 0
# 7 1 4 0
# 8 2 4 0
# 9 1 5 1
# 10 2 5 4