[R] apply and table

Jinsong Zhao jszhao at yeah.net
Sun May 19 16:22:40 CEST 2013

Hi there,

I have the following code:

z <- matrix(c("A", "A", "B", "B", "C", "C", "A", "B", "C"), ncol = 3)
apply(z, 2, table, c("A", "B", "C"))

which give correct results.

However, the following code:

apply(z[,1,drop=FALSE], 2, table, c("A", "B", "C"))

which does not give what I expect. I have been thought it should give 
the same result as:

apply(z, 2, table, c("A", "B", "C"))[[1]]

What's the difference? Does apply not apply to column vector?

Another question: how to output the table in squared matrix (or data 
frame)? For example:

 > table(c("C", "B", "B"), c("A", "B", "C"))

     A B C
   B 0 1 1
   C 1 0 0

I hope to get the result something like:

     A B C
   A 0 0 0
   B 0 1 1
   C 1 0 0

Is there a way that can output that?

Any suggestions will be really appreciated. Thanks in advance.


More information about the R-help mailing list