[R] output from table() in matrix form

Robin Hankin r.hankin at soc.soton.ac.uk
Wed Jan 5 13:18:24 CET 2005


Hi

How do I get the output from table() in matrix form?

If I have

R>  table(c(1,1,1,1,2,20))

  1  2 20
  4  1  1

I want

      [,1] [,2] [,3]
[1,]    1    2   20
[2,]    4    1    1


The problem is that names(table) is a vector of characters and I need 
the numeric values.

I am using

R>  rbind(as.integer(names(x)),x)




I thought tabulate() might be better as it takes an integer-valued 
vector, but it isn't
quite right because the default bins are 1:20 and  I don't want the 
zeroes.

The following is a little clunky:

R> x <- rbind(1:20,tabulate(c(1,1,1,1,2,20)))
R> x[,x[2,]>0]
      [,1] [,2] [,3]
[1,]    1    2   20
[2,]    4    1    1


Is there a better way?   It seems inelegant to coerce a character 
vector back to integers,
but OTOH  it's wasteful to have 20 bins when I only need 3.  My real 
application would have
maybe a dozen distinct (prime) integers in the range 2 up to about  1e4.





--
Robin Hankin
Uncertainty Analyst
Southampton Oceanography Centre
European Way, Southampton SO14 3ZH, UK
  tel  023-8059-7743




More information about the R-help mailing list