-2

How can i find the cross tabulation of the following two variables?

X Y
6 7 
8 8
9 10

I go like this:

X <- c(6,8,9)
Y <- c(7,8,10)
X <- factor(X)
Y <- factor(Y)    

I found the frequencies of X and Y with the following commands:

table(X)
table(Y)

but I don't know how to use them. I tried to print the matrix with the command

table(X,Y)

but it is not exactly the result I want, which will be like this:

  Y 6 7 8 9 10
X
6   0 1 0 0 0
7   0 0 0 0 0 
8   0 0 1 0 0
9   0 0 0 0 1
10  0 0 0 0 0 

The numbers 6,7,8,9,10 are all the different levels of X and Y.

Ben Bolker
  • 173,430
  • 21
  • 312
  • 389
k.atli
  • 33
  • 1
  • 6
  • It is unclear what you want; could you please provide an example of what the output should look like for the `X` and `Y` vectors above. `table(X, Y)` does produce a 3x3 grid though not a `matrix`. You can make it a `matrix` using `unclass(table(X, Y))`. – Barker Nov 22 '16 at 20:57
  • I edited my post above, check it :) – k.atli Nov 23 '16 at 14:09

1 Answers1

0

You need to tell table that there are levels not included in each variable. (Making X and Y into factors prematurely actually causes more problems than it's worth.)

X <- c(6,8,9)
Y <- c(7,8,10)
vals <- c(X,Y)
levs <- min(vals):max(vals)
table(factor(X,levs),factor(Y,levs))

If you start with factors you can use levs <- sort(union(levels(X),levels(Y))). In this case that would be annoying because R sorts factor levels alphabetically ("10" comes before "6").

Ben Bolker
  • 173,430
  • 21
  • 312
  • 389