4

I am trying to make a contingency (frequency) table using table() in R for two integer variables, but the default option in table does not include all the values in the range for each. For example:

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

returns:

  1 2 3
1 1 0 0
2 1 0 0 
3 0 1 0
5 0 0 1

I would like it to give:

  1 2 3
1 1 0 0
2 1 0 0 
3 0 1 0
4 0 0 0
5 0 0 1

This is a simple example where the value '4' isn't in one of the vectors. I know I could manipulate it into an array and add in a row of zero's, but I'm wondering if there's a simpler way to automatically do this for when the variables might span hundreds of (sparse) integer values.

Justina Pinch
  • 367
  • 1
  • 7

1 Answers1

6

A way to get this is

a=factor(c(1,2,3,5), levels=1:5)
b=factor(c(1,1,2,3), levels=1:5)
table(a,b)
G5W
  • 36,531
  • 10
  • 47
  • 80