More simplification in tapply() result
tapplySimpl.RdFor the case of more than two categories or indices (in INDEX),
traditional tapply(*, simplify = TRUE) still returns a
list when an array may seem more useful and natural. This is provided
by tapplySimpl() if the function FUN() is defined such
as to return a vector of the same length in all cases.
Arguments
- X
an atomic object, typically a vector. All these arguments are as in
tapply()and are passed totapply(..).- INDEX
list of (typically more than one) factors, each of same length as
X.- FUN
the function to be applied. For the result to be simplifiable,
FUN()must return a vector of always the same length.- ...
optional arguments to
FUN.
Value
If the above conditions are satisfied, the list returned from
r <- tapply(X, INDEX, FUN, ...) is simplified into an
array of rank \(1 + \#\{indices\}\), i.e.,
1+length(INDEX); otherwise, tapplySimpl() returns the list
r, i.e., the same as tapply().
See also
tapply(*, simplify=TRUE).
Examples
## Using tapply() would give a list (with dim() of a matrix);
## here we get 3-array:
data(esoph)
with(esoph, {
mima <<- tapplySimpl(ncases/ncontrols, list(agegp, alcgp), range)
stopifnot(dim(mima) == c(2, nlevels(agegp), nlevels(alcgp)))
})
aperm(mima)
#> , , 1
#>
#> 25-34 35-44 45-54 55-64 65-74 75+
#> 0-39g/day 0 0 0.000 0.0426 0.000 0.0588
#> 40-79 0 0 0.188 0.2903 0.429 0.0000
#> 80-119 0 0 0.231 1.0000 0.500 Inf
#> 120+ 0 0 2.000 1.0000 1.000 Inf
#>
#> , , 2
#>
#> 25-34 35-44 45-54 55-64 65-74 75+
#> 0-39g/day 0 0.0769 0.0222 2 0.40 0.5
#> 40-79 0 0.1500 2.5000 1 1.25 Inf
#> 80-119 0 0.0000 1.0000 Inf Inf Inf
#> 120+ Inf 2.0000 Inf 6 Inf Inf
#>