# `apply(X, MARGIN, FUN, ...)`reference

• Apply `FUN` over subarrays.
• Consider `MARGIN` as columns to keep
• `MARGIN` can be a vector of dimension number or name.
``````A <- rbind(c(1, 2, 3),
c(4, 5, 6),
c(7, 8, 9))
dimnames(A) <- list(player = NULL, round = NULL)
A``````
``````      round
player [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9
``````
``````# 1 means the first dim, or row.
# So, to keep rows, `sum()` is applied to row elements.
# So, the result is a vector of each player's total score
apply(A, 1, sum)``````
``````[1]  6 15 24
``````
``````# Player average
apply(A, "player", mean)``````
``````[1] 2 5 8
``````
``````# Round average
apply(A, "round", mean)``````
``````[1] 4 5 6
``````

# `sapply(X, FUN, ..., simplify = TRUE, USE.NAMES = TRUE)`reference

• `sapply` is similar to `lapply`, but it simplifies the result.
``l <- list(1, 2, 3)``
``lapply(l, function(x) x^2)``
``````[[1]]
[1] 1

[[2]]
[1] 4

[[3]]
[1] 9
``````
``sapply(l, function(x) x^2)``
``````[1] 1 4 9
``````

# `replicate(n, expr, simplify = "array")`reference

• Repeatedly evaluates `expr`
• Returns a vector, an array, or a list of the results
``replicate(3, print("hello"))``
``````[1] "hello"
[1] "hello"
[1] "hello"
[1] "hello" "hello" "hello"
``````

# `mapply(FUN, ...)`reference

Apply a function to multiple list or vector arguments

``````x <- c(1, 2, 3)
y <- c(4, 5, 6)
mapply(function(a, b) { a + b }, x, y)``````
``````[1] 5 7 9
``````

# `tapply(X, INDEX, FUN, …)`reference

• Apply a function to each cell of a ragged array(multiple groups mixed in an array)
• The combination of a vector and a labelling factor is an example of what is sometimes called a ragged array since the subclass sizes are possibly irregular.
``````x <- 1:5
y <- factor(c("a", "b", "a", "b", "c"))``````
``tapply(x, y, mean)``
``````a b c
2 3 5
``````
``tapply(x, y, length)``
``````a b c
2 2 1
``````

# `do.call(what, args)`reference

• Call a function by its name
• Pass arguments as `list`
``rnorm(n = 10, mean = 0, sd = 1)``
`````` [1] -0.266621955  0.511712080 -0.728687674 -0.003757919  2.028559127
[6]  2.063869831  2.230660146 -1.962791472  0.903502277  0.779437409
``````

Equivalent to

``do.call("rnorm", list(n = 10, mean = 0, sd = 1))``
`````` [1]  0.04329682 -0.33890374 -0.75751409 -1.68195845  0.47877042 -0.38845015
[7]  0.79256410  0.97123402 -0.30013421 -0.98092673
``````