Applies an element-wise operation between an array and the supplied statistics broadcast over the requested margins while preserving dimension names. Matches the semantics of [base::sweep()].

array_sweep(x, MARGIN, STATS, FUN = "*")

Arguments

x

Numeric array.

MARGIN

Integer or character vector identifying the margins over which `STATS` should be swept. Character margins are matched against the names of `dimnames(x)`.

STATS

Numeric array or vector that is broadcastable over `MARGIN`.

FUN

Character scalar choosing the operation. Supported values are `"+"`, `"-"`, `"*"`, and `"/"`.

Value

An array with the same shape (and dimnames) as `x` containing the swept result.

Examples

x <- array(1:12, dim = c(3, 4))
dimnames(x) <- list(country = c("A", "B", "C"), sector = c("X", "Y", "Z", "W"))
stats <- c(1, 2, 3)
array_sweep(x, MARGIN = "country", STATS = stats, FUN = "-")
#>        sector
#> country X Y Z W
#>       A 0 3 6 9
#>       B 0 3 6 9
#>       C 0 3 6 9