Cross Validated is a question and answer site for people interested in statistics, machine learning, data analysis, data mining, and data visualization. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a contingency table computed from the out of sample observations. In some cases not all classes are represented in the out of sample and hence do not appear. I want to coerce the contingency table to report zeros for classes not in the out of sample. How can I do it efficiently. For example my contingency table is

  x z
x 1 2
y 1 3
z 2 2

but i want it to look like

  x y z
x 1 0 2
y 1 0 3
z 2 0 2
share|improve this question

closed as off-topic by gung, Andy, Scortchi, ttnphns, Nick Stauner May 17 '14 at 20:20

  • This question does not appear to be about statistics within the scope defined in the help center.
If this question can be reworded to fit the rules in the help center, please edit the question.

This question appears to be off-topic because it is about how to use R's table function. – gung May 17 '14 at 13:56
sorry I did not realize I posted on CV while I meant to post to SO. admins please move it to SO. Thank you. – earthlink May 17 '14 at 20:31
up vote 3 down vote accepted

Read the manual. This is explained in the documentation for table(). You simply set useNA="ifany".

Your edit does not constitute a reproducible example. If setting the useNA argument does not resolve your problem, it may be that R doesn't recognize that that level of your factor exists. Assuming your column factor is f.c, try f.c <- factor(f.c, levels=c("x","y","z")) prior to calling table(). If that isn't the solution, you will need to add a truly reproducible example.

share|improve this answer
I had tried it but this does not solve my problem. I added some examples to show my problem. – earthlink May 17 '14 at 20:32
Thank you, that solved my problem. – earthlink May 21 '14 at 0:07
You're welcome. – gung May 21 '14 at 0:50

Not the answer you're looking for? Browse other questions tagged or ask your own question.