1

I have a binary matrix:

      S1 S2 S3 S4 S5 D1 D2 D3 D4
obs1  0  0  0  1  0  0  1  0  0
obs2  0  1  0  0  0  1  0  0  0
obs3  0  0  1  0  0  0  0  1  0
obs4  0  0  0  1  0  0  1  0  0
obs5  0  1  0  0  0  0  1  0  0
obs6  0  0  0  1  0  0  1  0  0

Each row of the matrix must contain the value 1 for the S group (S1, S2, S3, S4 or S5) and the value 1 for D group (D1, D2, D3 or D4).

How can I create a contingency table for the two groups based on two columns of the binary matrix where the value 1 appears? i.e., I would like to have this table format:

   D1 D2 D3 D4
S1 0  0  0  0
S2 1  1  0  0
S3 0  0  1  0
S4 0  3  0  0
S5 0  0  0  0

Here, for example, the value 3 is coming from obs1, obs4 and obs6, where the couple (S4,D2) take simultaniously 1 as value.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
sdhaoui
  • 369
  • 1
  • 10

2 Answers2

1

You can try:

table(cbind.data.frame(
  S=factor(max.col(x[,1:5]),levels=1:5,labels=paste0("S",1:5)),
  D=factor(max.col(x[,6:9]),levels=1:4,labels=paste0("D",1:4))
))
#    D
#S    D1 D2 D3 D4
#  S1  0  0  0  0
#  S2  1  1  0  0
#  S3  0  0  1  0
#  S4  0  3  0  0
#  S5  0  0  0  0
nicola
  • 24,005
  • 3
  • 35
  • 56
0

A nested apply

 t(apply(df[2:6], 2, function(x) apply(df[7:10], 2, function(y) sum(x==1 & y ==1))))
   D1 D2 D3 D4
S1  0  0  0  0
S2  1  1  0  0
S3  0  0  1  0
S4  0  3  0  0
S5  0  0  0  0
DatamineR
  • 10,428
  • 3
  • 25
  • 45