R/rvarapply.R
rvar_apply.Rd
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
.
rvar_apply(.x, .margin, .f, ...)
.x  An array or an 

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

.f  (function) The function to be applied. The function 
...  Optional arguments passed to 
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.
This function acts much like apply()
, except that the function passed to it (.f
)
must return rvar
s, 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 rvar
s where the result is not intended to
be simplified into an rvar
, you can use the standard apply()
, lapply()
,
sapply()
, or vapply()
functions.
as_rvar()
to convert objects to rvar
s. See rdo()
, rfun()
, and
rvar_rng()
for higherlevel interfaces for creating rvar
s.
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<4000>[2] mean ± sd: #> [1] 12 ± 0.29 13 ± 0.29rvar_apply(x, 2:3, rvar_mean)#> rvar<4000>[3,4] mean ± sd: #> [,1] [,2] [,3] [,4] #> [1,] 1.5 ± 0.70 7.5 ± 0.69 13.5 ± 0.71 19.5 ± 0.70 #> [2,] 3.5 ± 0.70 9.5 ± 0.71 15.5 ± 0.72 21.5 ± 0.70 #> [3,] 5.5 ± 0.71 11.5 ± 0.72 17.5 ± 0.71 23.5 ± 0.70