Examples for 'base::tapply'


Apply a Function Over a Ragged Array

Aliases: tapply

Keywords: iteration category

### ** Examples

require(stats)
groups <- as.factor(rbinom(32, n = 5, prob = 0.4))
tapply(groups, groups, length) #- is almost the same as
 9 15 16 18 
 1  1  2  1 
table(groups)
groups
 9 15 16 18 
 1  1  2  1 
## contingency table from data.frame : array with named dimnames
tapply(warpbreaks$breaks, warpbreaks[,-1], sum)
    tension
wool   L   M   H
   A 401 216 221
   B 254 259 169
tapply(warpbreaks$breaks, warpbreaks[, 3, drop = FALSE], sum)
tension
  L   M   H 
655 475 390 
n <- 17; fac <- factor(rep_len(1:3, n), levels = 1:5)
table(fac)
fac
1 2 3 4 5 
6 6 5 0 0 
tapply(1:n, fac, sum)
 1  2  3  4  5 
51 57 45 NA NA 
tapply(1:n, fac, sum, default = 0) # maybe more desirable
 1  2  3  4  5 
51 57 45  0  0 
tapply(1:n, fac, sum, simplify = FALSE)
$`1`
[1] 51

$`2`
[1] 57

$`3`
[1] 45

$`4`
NULL

$`5`
NULL
tapply(1:n, fac, range)
$`1`
[1]  1 16

$`2`
[1]  2 17

$`3`
[1]  3 15

$`4`
NULL

$`5`
NULL
tapply(1:n, fac, quantile)
$`1`
   0%   25%   50%   75%  100% 
 1.00  4.75  8.50 12.25 16.00 

$`2`
   0%   25%   50%   75%  100% 
 2.00  5.75  9.50 13.25 17.00 

$`3`
  0%  25%  50%  75% 100% 
   3    6    9   12   15 

$`4`
NULL

$`5`
NULL
tapply(1:n, fac, length) ## NA's
 1  2  3  4  5 
 6  6  5 NA NA 
tapply(1:n, fac, length, default = 0) # == table(fac)
1 2 3 4 5 
6 6 5 0 0 
## Don't show: 
stopifnot(all.equal(
  unname(unclass(table(fac))),
  unname(        tapply(1:n, fac, length, default = 0))))
## End(Don't show)
## example of ... argument: find quarterly means
tapply(presidents, cycle(presidents), mean, na.rm = TRUE)
       1        2        3        4 
58.44828 56.43333 57.22222 53.07143 
ind <- list(c(1, 2, 2), c("A", "A", "B"))
table(ind)
     ind.2
ind.1 A B
    1 1 0
    2 1 1
tapply(1:3, ind) #-> the split vector
[1] 1 2 4
tapply(1:3, ind, sum)
  A  B
1 1 NA
2 2  3
## Some assertions (not held by all patch propsals):
nq <- names(quantile(1:5))
stopifnot(
  identical(tapply(1:3, ind), c(1L, 2L, 4L)),
  identical(tapply(1:3, ind, sum),
            matrix(c(1L, 2L, NA, 3L), 2, dimnames = list(c("1", "2"), c("A", "B")))),
  identical(tapply(1:n, fac, quantile)[-1],
            array(list(`2` = structure(c(2, 5.75, 9.5, 13.25, 17), names = nq),
                 `3` = structure(c(3, 6, 9, 12, 15), names = nq),
                 `4` = NULL, `5` = NULL), dim=4, dimnames=list(as.character(2:5)))))

[Package base version 4.2.3 Index]