0

Hi i have two vectors: predicts and targets and i have 3 classes "A", "B" and "C".

  targets = c("B", "A", "C", "C", "B")
  predicts = c("B", "B", "C", "C", "B")

and i want to create confusion matrix using this data. I want my output to look like this:

    A B C
  A 0 1 0
  B 0 2 0
  C 0 0 2

but for table(targets, predicts) i get this:

    B C
  A 1 0
  B 2 0
  C 0 2

Is it possible to fill the table with default values when missing class, like 0 for example?

cvzx
  • 17
  • 7

1 Answers1

0

We can convert to factor with levels specified as all the unique values in both datasets and then use the table

lvls <- sort(union(targets, predicts))
table(factor(targets,levels = lvls), factor(predicts, levels = lvls))

-output

    A B C
  A 0 1 0
  B 0 2 0
  C 0 0 2
akrun
  • 874,273
  • 37
  • 540
  • 662