[R] frequency table

Robin Hankin r.hankin at auckland.ac.nz
Wed Jun 25 06:13:18 CEST 2003


Professor Baron writes:

> 
> A neat trick with table() is that you can use it to tabulate
> columns of a matrix (for example) with:
> 
> apply(mymatrix,2,table)
> 

OK, I'll bite:

> x1 <- matrix(1:3,7,4,byrow=T)
Warning message: 
Replacement length not a multiple of the elements to replace in matrix(...) 
> dim(x1)
[1] 7 4
> apply(x1,2,table)
  [,1] [,2] [,3] [,4]
1    3    2    2    3
2    2    3    2    2
3    2    2    3    2
> 

fine (this is what I would have expected).  But now...

> x2 <- matrix(c(1,2,1,2,1,3,1,3,1,1,1,2,2,2,2,3,2,3,3,2,3,1,1,3,3,1,3,3),7,4)
> dim(x2)
[1] 7 4
> apply(x2,2,table)
[[1]]

1 2 3 
4 2 1 

[[2]]

1 2 3 
3 3 1 

[[3]]

2 3 
3 4 

[[4]]

1 3 
3 4 


Why the difference in output format?

[presumably it's because table() cuts its cloth accordingly, unlike
tabulate()...but how can apply() know this?  My real question would be
how to turn an expression like the list given by apply(x2,2,table)
into a nice matrix].



-- 

Robin Hankin, Lecturer,
School of Geography and Environmental Science
Tamaki Campus
Private Bag 92019 Auckland
New Zealand

r.hankin at auckland.ac.nz
tel 0064-9-373-7599 x6820; FAX 0064-9-373-7042




More information about the R-help mailing list