Robin,
the initial output from apply() is always in the form you have below, but if
it can be 'simplified' into a structure like the matrix, it does so.
The
same thing happens with sapply().
If you want to produce a nice matrix as the out put you have to ensure that
the simplification is possible. Here is one way.
> apply(x2, 2, function(x, v) table(factor(x, levels=v)),
sort(unique(as.vector(x2))))
[,1] [,2] [,3] [,4]
1 4 3 0 3
2 2 3 3 0
3 1 1 4 4
Bill Venables.
-----Original Message-----
From: Robin Hankin [mailto:r.hankin at auckland.ac.nz]
Sent: Wednesday, June 25, 2003 2:13 PM
To: baron at cattell.psych.upenn.edu
Cc: r-help at stat.math.ethz.ch; toth at host.sk
Subject: Re: [R] frequency table
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
______________________________________________
R-help at stat.math.ethz.ch mailing list
https://www.stat.math.ethz.ch/mailman/listinfo/r-help