Jonas Schmedtmann
Jonas Schmedtmann

Reputation: 87

How to get a square table?

I've got the following code to create a classification table in R:

> table(class = class1, truth = valid[,1])
     1  2   3  4  5  6  7  8  9 10 11 12
1  357 73   0  0 47  0  5 32 20  0  4  7
2   25 71   0  0 23  4  1  0  2  1  8  3
3    1  2 120  1  5  0  1  0  0  0  0  0
4    0  0   0 77  0  0  0  0  1  0  0  0
5   15 27   0  0 67  6  7  0  4  1  5  7
6    1  2   0  0  2 44  0  0  0  7  7  0
7    1  1   0  0 10  0 66  0  1  0  1  7
9    1  0   0  0  3  0  0  2  8  0  0  2
10   1  1   0  0  1  6  0  0  0 17  0  0
11   0  7   0  0  3  1  0  0  0  4 10  2
12   0  1   0  0  1  0  0  0  0  0  0  1

However, I need this table to be a square (line 8 is missing in this example), i.e. the number of rows should equal the number of columns, and I need the rownames and colnames to be preserved. The missing line should be filled with zeros. Any way of doing this?

Upvotes: 1

Views: 309

Answers (1)

nico
nico

Reputation: 51680

The problem most probably comes from a difference in levels.

Try copying the levels from valid to class1:

class1 <- factor(class1, levels=levels(valid[,1])
table(class = class1, truth = valid[,1])

Upvotes: 1

Related Questions