Learn R Programming

posterior (version 1.6.0)

rvar_rng: Create random variables from existing random number generators

Description

Specialized alternative to rdo() or rfun() for creating rvars from existing random-number generator functions (such as rnorm(), rbinom(), etc).

Usage

rvar_rng(.f, n, ..., ndraws = NULL)

Value

A single-dimensional rvar of length n.

Arguments

.f

(function) A function (or string naming a function) representing a random-number generating function that follows the pattern of base random number generators (like rnorm(), rbinom(), etc). It must:

  • Have a first argument, n, giving the number of draws to take from the distribution

  • Have vectorized parameter arguments

  • Return a single vector of length n

n

(positive integer) The length of the output rvar vector (not the number of draws).

...

Arguments passed to .f. These arguments may include rvars, so long as they are vectors only (no multidimensional rvars are allowed).

ndraws

(positive integer) The number of draws used to construct the returned random variable if no rvars are supplied in .... If NULL, getOption("posterior.rvar_ndraws") is used (default 4000). If ... contains rvars, the number of draws in the provided rvars is used instead of the value of this argument.

Details

This function unwraps the arrays underlying the input rvars in ... and then passes them to .f, relying on the vectorization of .f to evaluate it across draws from the input rvars. This is why the arguments of .f must be vectorized. It asks for n times the number of draws in the input rvars (or ndraws if none are given) draws from the random number generator .f, then reshapes the output from .f into an rvar with length n.

rvar_rng() is a fast alternative to rdo() or rfun(), but you must ensure that .f satisfies the preconditions described above for the result to be correct. Most base random number generators satisfy these conditions. It is advisable to test against rdo() or rfun() (which should be correct, but slower) if you are uncertain.

See Also

Other rfun: rdo(), rfun()

Examples

Run this code

mu <- rvar_rng(rnorm, 10, mean = 1:10, sd = 1)
sigma <- rvar_rng(rgamma, 1, shape = 1, rate = 1)
x <- rvar_rng(rnorm, 10, mu, sigma)
x

Run the code above in your browser using DataLab