| apply_dpqr | R Documentation |
distributions3 objectsVarious utility functions to implement methods for distributions with a
unified workflow, in particular to facilitate working with vectorized
distributions3 objects.
These are particularly useful in the computation of densities, probabilities, quantiles,
and random samples when classical d/p/q/r functions are readily available for
the distribution of interest.
apply_dpqr(d, FUN, at, elementwise = NULL, drop = TRUE, type = NULL, ...)
get_deriv_names(p, which = NULL, expand = FALSE, check = TRUE)
max_length(..., check = TRUE)
apply_deriv(d, x, FUN, which, drop = TRUE, check = TRUE, ...)
make_support(min, max, d, drop = TRUE)
make_positive_integer(n)
d |
A |
FUN |
Function to be computed. |
at |
Specification of values at which |
elementwise |
logical. Should each element of |
drop |
logical. Should the result be simplified to a vector if possible (by
dropping the dimension attribute)? If |
type |
Character string used for naming, typically one of |
... |
Arguments to be passed to |
p |
character vector with the names of the parameters of a distribution. |
which |
character vector, named or unnamed. When calculating cross-derivatives a named vector is typically used avoiding to calculate the cross-derivatives twice even if they are identical (symmetric Hessian matrix; see 'Examples'). |
expand |
logical. If set to |
check |
logical. Should the function check that all objects in |
x |
numeric. Specification of values at which |
min, max |
Numeric vectors. Minima and maxima of the supports of a |
n |
numeric. Number of observations for computing random draws. If |
apply_dpqr(): Numeric vector or matrix, possibly named.
get_deriv_names(): Named character vector with all available or
requested derivative names.
max_length(): Single integer with the maximum length of all
parameters (objects) provided via the ... argument. If check = TRUE and
the length of all parameters does not match, an error will be thrown.
apply_deriv(): Numeric vector or matrix (possibly named).
make_support(): Named vector (if drop = TRUE and length(d) = 1L)
or named matrix with the support of the distribution.
make_positive_integer(): Single positive integer. If the length of
the object on argument n is larger than one, the length of the object is
returned. Else n is converted to integer if possible or an error is thrown.
## Implementing a new distribution based on the provided utility functions
## Illustration: Gaussian distribution
## Note: Gaussian() is really just a copy of Normal() with a different class/distribution name
## Generator function for the distribution object.
Gaussian <- function(mu = 0, sigma = 1) {
stopifnot(
"parameter lengths do not match (only scalars are allowed to be recycled)" =
length(mu) == length(sigma) | length(mu) == 1 | length(sigma) == 1
)
d <- data.frame(mu = mu, sigma = sigma)
class(d) <- c("Gaussian", "distribution")
d
}
## Set up a vector Y containing four Gaussian distributions:
Y <- Gaussian(mu = 1:4, sigma = c(1, 1, 2, 2))
Y
## Extract the underlying parameters:
as.matrix(Y)
## Extractor functions for moments of the distribution include
## mean(), variance(), skewness(), kurtosis().
## These can be typically be defined as functions of the list of parameters.
mean.Gaussian <- function(x, ...) {
rlang::check_dots_used()
setNames(x$mu, names(x))
}
## Analogously for other moments, see distributions3:::variance.Normal etc.
mean(Y)
## The support() method should return a matrix of "min" and "max" for the
## distribution. The make_support() function helps to set the right names and
## dimension.
support.Gaussian <- function(d, drop = TRUE, ...) {
min <- rep(-Inf, length(d))
max <- rep(Inf, length(d))
make_support(min, max, d, drop = drop)
}
support(Y)
## Evaluating certain functions associated with the distribution, e.g.,
## pdf(), log_pdf(), cdf() quantile(), random(), etc. The apply_dpqr()
## function helps to call the typical d/p/q/r functions (like dnorm,
## pnorm, etc.) and set suitable names and dimension.
pdf.Gaussian <- function(d, x, elementwise = NULL, drop = TRUE, ...) {
FUN <- function(at, d) dnorm(x = at, mean = d$mu, sd = d$sigma, ...)
apply_dpqr(d = d, FUN = FUN, at = x, type = "density", elementwise = elementwise, drop = drop)
}
## Evaluate all densities at the same argument (returns vector):
pdf(Y, 0)
## Evaluate all densities at several arguments (returns matrix):
pdf(Y, c(0, 5))
## Evaluate each density at a different argument (returns vector):
pdf(Y, 4:1)
## Force evaluation of each density at a different argument (returns vector)
## or at all arguments (returns matrix):
pdf(Y, 4:1, elementwise = TRUE)
pdf(Y, 4:1, elementwise = FALSE)
## Drawing random() samples also uses apply_dpqr() with the argument
## n assured to be a positive integer.
random.Gaussian <- function(x, n = 1L, drop = TRUE, ...) {
n <- make_positive_integer(n)
if (n == 0L) {
return(numeric(0L))
}
FUN <- function(at, d) rnorm(n = at, mean = d$mu, sd = d$sigma)
apply_dpqr(d = x, FUN = FUN, at = n, type = "random", drop = drop)
}
## One random sample for each distribution (returns vector):
random(Y, 1)
## Several random samples for each distribution (returns matrix):
random(Y, 3)
## For further analogous methods see the "Normal" distribution provided
## in distributions3.
methods(class = "Normal")
## ----------------
## get_deriv_names(): Get names of derivatives including cross-derivatives
## if `expand` is set TRUE, and checks/selects the names requested by
## the user if `which` is not NULL.
get_deriv_names(c("mu", "sigma"))
get_deriv_names(c("mu", "sigma"), expand = TRUE)
get_deriv_names(c("mu", "sigma"), which = c("mu:sigma", "sigma"), expand = TRUE)
## ----------------
## max_length(): Calculate maximum length of a series of objects.
## If check is set FALSE, the maximum length is returned
max_length(a = 1, b = seq_len(10), c = seq_len(5), check = FALSE)
max_length(Normal(mu = 1:3, sigma = 2), 10:11, check = FALSE)
## If check is TRUE (default) all objects must be of length 1
## or length 'N', where 'N' is the length of the longest object.
max_length(Normal(mu = 1:3, sigma = 2), 10)
max_length(Normal(mu = 1:3, sigma = 2), 10:12)
## Not run:
## Non-suitable lenghts, throws error (check = TRUE)
max_length(d = Normal(mu = 1:3, sigma = 2), x = 10:15)
## End(Not run)
## ----------------
## apply_deriv(): Minimal example on how to use apply_deriv to calculate
## score/hessian based on the Uniform distribution for demonstration.
## Creating distributions object
d <- Uniform(a = c(2, 3), b = c(0.5, 0.5))
## Function for calculating score of the Uniform distribution
scr <- function(par, d, x) switch(par,
"a" = 0 * x + 1 / (d$b - d$a),
"b" = 0 * x - 1 / (d$b - d$a))
## Function for calculating hessian of the Uniform distribution
hess <- function(par, d, x) switch(par,
"a" = 0 * x + 1 / (d$b - d$a)^2,
"b" = 0 * x + 1 / (d$b - d$a)^2,
-(0 * x + 1 / (d$b - d$a)^2)) # Cross-derivatives
## Calculating score: first derivative of the likelihood | parameters
apply_deriv(d = d, x = 1.5, FUN = scr, which = c("a", "b"))
score(d, 1.5) # using method for comparison
## Calculating hessian: second derivative of the likelihood | parameters,
## including cross-derivatives
which <- get_deriv_names(c("a", "b"), expand = TRUE)
apply_deriv(d = d, x = 1.5, FUN = hess, which = which)
hessian(d, 1.5) # using method for comparison
## ----------------
## make_support(): Creating support matrix/support vector for distribution
## objects (see also ?support).
d <- setNames(Normal(1:3, 3:1), LETTERS[1:3])
make_support(min = rep(-Inf, 3L), max = rep(Inf, 3L), d)
make_support(0, Inf, Poisson(1.5), drop = TRUE)
## ----------------
## make_positive_integer()
make_positive_integer(5.0)
make_positive_integer(TRUE)
make_positive_integer(LETTERS[1:10])
## Not run:
make_positive_integer("foo") # Throws error
## End(Not run)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.