The function is modeled after `vapply`, but always returns a matrix with one row for each iteration. You need to provide the number of elements each function call produces beforehand (i.e. the number of resulting columns). For a more flexible version where you don't need to provide the number of columns see msply_dbl

mply_dbl(x, FUN, ncol = 1, ...)

msply_dbl(x, FUN, ...)

Arguments

x

a vector that will be passed to `vapply` or a matrix that will be passed to apply with MARGIN=1.

FUN

the function that returns a vector of length ncol

ncol

the length of the vector returned by `FUN`.

...

additional arguments to FUN

Value

a matrix of size length(x) x ncol

Functions

  • mply_dbl: apply function that always returns a numeric matrix

  • msply_dbl: flexible version that automatically infers the number of columns

Examples

# Behaves similar to sapply(), but it always returns a matrix t(sapply(1:5, function(i) c(i - i/3, i, i + i/3)))
#> [,1] [,2] [,3] #> [1,] 0.6666667 1 1.333333 #> [2,] 1.3333333 2 2.666667 #> [3,] 2.0000000 3 4.000000 #> [4,] 2.6666667 4 5.333333 #> [5,] 3.3333333 5 6.666667
proDA:::mply_dbl(1:5, function(i) c(i - i/3, i, i + i/3), ncol=3)
#> [,1] [,2] [,3] #> [1,] 0.6666667 1 1.333333 #> [2,] 1.3333333 2 2.666667 #> [3,] 2.0000000 3 4.000000 #> [4,] 2.6666667 4 5.333333 #> [5,] 3.3333333 5 6.666667
# Which can avoid some bad surprises t(sapply(1:5, identity))
#> [,1] [,2] [,3] [,4] [,5] #> [1,] 1 2 3 4 5
proDA:::mply_dbl(1:5, identity)
#> [,1] #> [1,] 1 #> [2,] 2 #> [3,] 3 #> [4,] 4 #> [5,] 5
# Works also with matrix input mat <- matrix(1:20, ncol=4) mat
#> [,1] [,2] [,3] [,4] #> [1,] 1 6 11 16 #> [2,] 2 7 12 17 #> [3,] 3 8 13 18 #> [4,] 4 9 14 19 #> [5,] 5 10 15 20
proDA:::msply_dbl(mat, function(i) rep(i, each=2))
#> [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] #> [1,] 1 1 6 6 11 11 16 16 #> [2,] 2 2 7 7 12 12 17 17 #> [3,] 3 3 8 8 13 13 18 18 #> [4,] 4 4 9 9 14 14 19 19 #> [5,] 5 5 10 10 15 15 20 20