R: Apply Functions Over Array Margins via Futures

future_apply {future.apply} | R Documentation

## Apply Functions Over Array Margins via Futures

### Description

`future_apply()` implements `base::apply()` using future with perfect replication of results, regardless of future backend used. It returns a vector or array or list of values obtained by applying a function to margins of an array or matrix.

### Usage

    future_apply(X, MARGIN, FUN, ...)

### Arguments

`X` | an array, including a matrix.
`MARGIN` | A vector giving the subscripts which the function will be applied over. For example, for a matrix `1` indicates rows, `2` indicates columns, `c(1, 2)` indicates rows and columns. Where `X` has named dimnames, it can be a character vector selecting dimension names.
`FUN` | A function taking at least one argument.
`...` | (optional) Additional arguments passed to `FUN()`, except `future.*` arguments, which are passed on to `future_lapply()` used internally.

### Value

Returns a vector or array or list of values obtained by applying a function to margins of an array or matrix. See `base::apply()` for details.

### Author(s)

The implementations of `future_apply()` is adopted from the source code of the corresponding base R function, which is licensed under GPL (>= 2) with 'The R Core Team' as the copyright holder.

### Examples

    ## ---------------------------------------------------------
    ## apply()
    ## ---------------------------------------------------------
    X <- matrix(c(1:4, 1, 6:8), nrow = 2L)

    Y0 <- apply(X, MARGIN = 1L, FUN = table)
    Y1 <- future_apply(X, MARGIN = 1L, FUN = table)
    print(Y1)
    stopifnot(all.equal(Y1, Y0, check.attributes = FALSE)) ## FIXME

    Y0 <- apply(X, MARGIN = 1L, FUN = stats::quantile)
    Y1 <- future_apply(X, MARGIN = 1L, FUN = stats::quantile)
    print(Y1)
    stopifnot(all.equal(Y1, Y0))

    ## ---------------------------------------------------------
    ## Parallel Random Number Generation
    ## ---------------------------------------------------------

    ## Regardless of the future plan, the number of workers, and
    ## where they are, the random numbers produced are identical

    X <- matrix(c(1:4, 1, 6:8), nrow = 2L)

    plan(multiprocess)
    Y1 <- future_apply(X, MARGIN = 1L, FUN = sample, future.seed = 0xBEEF)
    print(Y1)

    plan(sequential)
    Y2 <- future_apply(X, MARGIN = 1L, FUN = sample, future.seed = 0xBEEF)
    print(Y2)

    stopifnot(all.equal(Y1, Y2))

[Package future.apply version 1.0.1 Index]