rvar_apply: Random variable resulting from a function applied over...

View source: R/rvar-apply.R

rvar_applyR Documentation

Random variable resulting from a function applied over margins of an array or random variable

Description

Returns an rvar obtained by applying a function to margins of an array or rvar. Acts like apply(), except that the function supplied (.f) should return an rvar, and the final result is always an rvar.

Usage

rvar_apply(.x, .margin, .f, ...)

Arguments

.x

An array or an rvar.

.margin

(multiple options) The subscripts which the function will be applied over:

  • An integer vector. E.g., for a matrix 1 indicates rows, 2 indicates columns, c(1, 2) indicates rows and columns.

  • A character vector of dimension names if .x has named dimensions.

.f

(function) The function to be applied. The function .f must return an rvar and the dimensions of the result of .f applied to each margin of .x must be able to be broadcasted to a common shape (otherwise the resulting rvar cannot be simplified). See Details.

...

Optional arguments passed to .f.

Details

This function acts much like apply(), except that the function passed to it (.f) must return rvars, and the result is simplified into an rvar. Unlike apply(), it also keeps the dimensions of the returned values along each margin, rather than simplifying each margin to a vector, and if the results of .f do not all have the same dimensions, it applies the rvar broadcasting rules to bind results together rather than using vector recycling.

If you wish to apply functions over rvars where the result is not intended to be simplified into an rvar, you can use the standard apply(), lapply(), sapply(), or vapply() functions.

Value

An rvar.

If the result of each call to .f returns an rvar of dimension d after being broadcast to a common shape, then rvar_apply() returns an rvar of dimension c(d, dim(.x)[.margin]). If the last dimension of the result would be 1, it is dropped (other dimensions equal to 1 are retained). If d is 0, the result has length 0 but not necessarily the 'correct' dimension.

See Also

as_rvar() to convert objects to rvars. See rdo(), rfun(), and rvar_rng() for higher-level interfaces for creating rvars.

Examples


set.seed(3456)
x <- rvar_rng(rnorm, 24, mean = 1:24)
dim(x) <- c(2,3,4)

# we can find the distributions of marginal means of the above array
# using rvar_mean along with rvar_apply
rvar_apply(x, 1, rvar_mean)
rvar_apply(x, 2:3, rvar_mean)


posterior documentation built on Nov. 2, 2023, 5:56 p.m.