0

I want to make a contingency table with observations and their predictions based on a neural network. Since I want positives to be on the diagonal, I would like my table to be squared, regardless if there are rows with just 0's. That is, I would like to have

   b
a   a b c d e f g
  a 1 0 1 0 2 1 0
  b 0 0 0 0 0 0 0
  c 0 0 0 0 0 0 0
  d 2 3 1 2 2 3 2
  e 1 2 1 1 0 1 3
  f 0 0 0 0 0 0 0
  g 4 2 1 0 3 1 0

Instead of:

> set.seed(1)
> b<-sample(letters[1:7],40,rep=TRUE)
> a<-sample(letters[1:4],40,rep=TRUE)
> 
> table(a,b)
   b
a   a b c d e f g
  a 1 0 1 0 2 1 0
  d 2 3 1 2 2 3 2
  e 1 2 1 1 0 1 3
  g 4 2 1 0 3 1 0

How can I do this?

paulgr
  • 89
  • 6

1 Answers1

1

Convert a and b to factor with levels as union of both :

tmp <- sort(union(a, b))
table(factor(a, levels = tmp), factor(b, levels = tmp))

#    a b c d e f g
#  a 0 1 1 2 2 1 4
#  b 2 1 1 1 2 3 2
#  c 4 0 1 2 0 1 1
#  d 0 1 1 1 3 1 1
#  e 0 0 0 0 0 0 0
#  f 0 0 0 0 0 0 0
#  g 0 0 0 0 0 0 0
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213