apply() tries to be a bit smart about what it does (sometimes maybe too
smart), but it actually is pretty useful a lot of the time. It's extremely
widely used, so changing the behavior is not an option -- changing the
behavior would break a lot of existing code. (Personally, I'd prefer it if
apply() put its dimensions back together in a slightly more intelligent
way, i.e., if apply(x, 1, c) and apply(x, 2, c) returned the same thing,
but apply is how it is.)
In situations where you don't want apply() to try to construct a matrix
from your results, you can wrap the results in a list, to force apply() to
return just a list of results, e.g. (the outer lapply() strips off an
unnecessary level of list depth):
b2 - lapply(apply (a, 1, function(x) list(table(x))), [[, 1)
length(b2)
[1] 4
b2[[1]]
x
1 2 6 7
2 1 1 1
attributes(b2[[1]])
$dim
[1] 4
$dimnames
$dimnames$x
[1] 1 2 6 7
$class
[1] table
Your particular case might benefit from more information given to table,
which allows it to provide results in a more uniform format, e.g.:
b1 - apply (a, 1, function(x) table(factor(x, levels=0:9)))
b1
[,1] [,2] [,3] [,4]
00100
12112
21001
30100
40220
50011
61001
71000
80010
90000
hope this helps,
Tony Plate
At Tuesday 10:42 AM 8/24/2004, [EMAIL PROTECTED] wrote:
a - matrix (c(
7, 1, 1, 2, 6,
3, 4, 0, 1, 4,
5, 1, 8, 4, 4,
6, 1, 1, 2, 5), nrow=4, byrow=TRUE)
b - apply (a, 1, table)
apply documentation says clearly that if the rows of the result of FUN
are the same length, then an array will be returned. And column-major
would be the appropriate order in R. But b above is pretty opaque
compared to what one would expect, and what one would get from apply (
, , table) if the rows were not of equal length. One needs to do
something like
n - matrix (apply (a, 1, function (x) unique (sort (x))), nrow=nrow(a))
to get the corresponding names of b to figure out the counts.
Denis White
__
[EMAIL PROTECTED] mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
__
[EMAIL PROTECTED] mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html