Function that create functions that can accept and/or produce rvar
s.
rfun(.f, rvar_args = NULL, rvar_dots = TRUE, ndraws = NULL)
(multiple options) A function to turn into a function that accepts and/or produces random variables:
A function
A one-sided formula that can be parsed by rlang::as_function()
(character vector) The names of the arguments of .f
that
should be allowed to accept rvar
s as arguments. If NULL
(the
default), all arguments to .f
are turned into arguments that accept
rvar
s, including arguments passed via ...
(if rvar_dots
is TRUE
).
(logical) Should dots (...
) arguments also be converted?
Only applies if rvar_args
is NULL
(i.e., all arguments are allowed to
be rvar
s).
(positive integer). The number of draws used to construct new
random variables if no rvar
s are supplied as arguments to the
returned function. If NULL
, getOption("posterior.rvar_ndraws")
is used
(default 4000
). If any arguments to the returned function contain
rvar
s, the number of draws in the provided rvar
s is used instead of
the value of this argument.
A function with the same argument specification as .f
, but which can accept and return
rvar
s.
This function wraps an existing function (.f
) such that it returns rvar
s containing
whatever type of data .f
would normally return.
The returned function, when called, executes .f
possibly multiple times, once for each draw of
the rvar
s passed to it, then returns a new
rvar
representing the output of those function evaluations. If the arguments contain no rvar
s,
then .f
will be executed ndraws
times and an rvar
with that many draws returned.
Functions created by rfun()
are not necessarily fast (in fact in some cases they may be very slow), but
they have the advantage of allowing a nearly arbitrary R functions to be executed against rvar
s
simply by wrapping them with rfun()
. This makes it especially useful as a prototyping
tool. If you create code with rfun()
and it is unacceptably slow for your application,
consider rewriting it using math operations directly on rvar
s (which should be fast),
using rvar_rng()
, and/or using operations directly on the arrays that back the rvar
s
(via draws_of()
).
rvar_norm <- rfun(rnorm)
rvar_gamma <- rfun(rgamma)
mu <- rvar_norm(10, mean = 1:10, sd = 1)
sigma <- rvar_gamma(1, shape = 1, rate = 1)
x <- rvar_norm(10, mu, sigma)
x
#> rvar<4000>[10] mean ± sd:
#> [1] 1.0 ± 1.7 2.0 ± 1.8 3.0 ± 1.7 3.9 ± 1.8 5.0 ± 1.8 6.0 ± 1.7
#> [7] 7.0 ± 1.7 8.0 ± 1.8 9.0 ± 1.7 10.0 ± 1.7