Apply functions
Table of Contents
apply(X, MARGIN, FUN, ...)
lapply(X, FUN, ...)
sapply(X, FUN, ..., simplify = TRUE, USE.NAMES = TRUE)
replicate(n, expr, simplify = "array")
mapply(FUN, ...)
tapply(X, INDEX, FUN, …)
do.call(what, args)
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.
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
[1] 2 5 8
[1] 4 5 6
lapply(X, FUN, ...)
reference
sapply(X, FUN, ..., simplify = TRUE, USE.NAMES = TRUE)
reference
sapply
is similar tolapply
, but it simplifies the result.
[[1]]
[1] 1
[[2]]
[1] 4
[[3]]
[1] 9
[1] 1 4 9
replicate(n, expr, simplify = "array")
reference
- Repeatedly evaluates
expr
- Returns a vector, an array, or a list of the results
[1] "hello"
[1] "hello"
[1] "hello"
[1] "hello" "hello" "hello"
mapply(FUN, ...)
reference
Apply a function to multiple list or vector arguments
[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.
a b c
2 3 5
a b c
2 2 1
do.call(what, args)
reference
- Call a function by its name
- Pass arguments as
list
[1] -0.266621955 0.511712080 -0.728687674 -0.003757919 2.028559127
[6] 2.063869831 2.230660146 -1.962791472 0.903502277 0.779437409
Equivalent to
[1] 0.04329682 -0.33890374 -0.75751409 -1.68195845 0.47877042 -0.38845015
[7] 0.79256410 0.97123402 -0.30013421 -0.98092673