Borealis Borealis - 3 years ago 56
R Question

How to create an error (aka confusion) matrix in R?

How can I generate an error (aka confusion) matrix in R?

Let's start with some sample data:

a = c(1,2,3,4,5,1,2,2,3,4,2,1,4,5,5,1)
b = c(1,2,3,4,5,1,2,2,3,4,2,2,4,5,2,1)


This is what I am aiming to achieve based on the sample data:

[,1] [,2] [,3] [,4] [,5] [total]
[,1] 3 1 4
[,2] 4 4
[,3] 2 2
[,4] 3 3
[,5] 1 3 4
[total]3 6 2 3 3 16


I can create a simple cross tabulation matrix using
table()
, however I cannot seem to get the row, column and overall totals.

> table(a,b)
b
a 1 2 3 4 5
1 3 1 0 0 0
2 0 4 0 0 0
3 0 0 2 0 0
4 0 0 0 3 0
5 0 1 0 0 2

Answer Source

To get row, column, and overall totals, just use addmargins:

> addmargins(table(a, b))
     b
a      1  2  3  4  5 Sum
  1    3  1  0  0  0   4
  2    0  4  0  0  0   4
  3    0  0  2  0  0   2
  4    0  0  0  3  0   3
  5    0  1  0  0  2   3
  Sum  3  6  2  3  2  16
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download