| Title: | Extra Functionality for the 'xpose' Package |
| Version: | 0.2.0 |
| Description: | Adding some at-present missing functionality, or functions unlikely to be added to the base 'xpose' package. This includes some diagnostic plots that have been missing in translation from 'xpose4', but also some useful features that truly extend the capabilities of what can be done with 'xpose'. These extensions include the concept of a set of 'xpose' objects, and diagnostics for likelihood-based models. |
| License: | MIT + file LICENSE |
| Encoding: | UTF-8 |
| Imports: | checkmate, cli, colorspace, conflicted, dplyr (≥ 1.1.2), forcats (≥ 1.0.0), GGally, ggplot2 (≥ 3.4.2), glue, grDevices, grid, lifecycle, magrittr, pmxcv, purrr (≥ 1.0.1), readr (≥ 2.1.4), rlang, stats, stringr (≥ 1.5.0), tibble (≥ 3.2.1), tidyr (≥ 1.3.0), tidyselect, utils, vctrs, xpose |
| Suggests: | bbr, callr, DiagrammeR, knitr, nlmixr2, nlmixr2data, nlmixr2est, pkgload, rmarkdown, rxode2, spelling, testthat (≥ 3.0.0), vdiffr, xpose.nlmixr2 |
| Config/testthat/edition: | 3 |
| Depends: | R (≥ 3.5) |
| LazyData: | true |
| VignetteBuilder: | knitr |
| URL: | https://jprybylski.github.io/xpose.xtras/, https://github.com/jprybylski/xpose.xtras |
| Language: | en-US |
| Config/Needs/website: | rmarkdown |
| Config/roxygen2/version: | 8.0.0 |
| Additional_repositories: | https://mpn.metworx.com/snapshots/stable/2026-06-25 |
| NeedsCompilation: | no |
| Packaged: | 2026-07-26 17:50:17 UTC; jprybylski |
| Author: | John Prybylski |
| Maintainer: | John Prybylski <jprybylski@gmail.com> |
| Repository: | CRAN |
| Date/Publication: | 2026-07-26 18:30:02 UTC |
xpose.xtras: Extra Functionality for the 'xpose' Package
Description
Adding some at-present missing functionality, or functions unlikely to be added to the base 'xpose' package. This includes some diagnostic plots that have been missing in translation from 'xpose4', but also some useful features that truly extend the capabilities of what can be done with 'xpose'. These extensions include the concept of a set of 'xpose' objects, and diagnostics for likelihood-based models.
Author(s)
Maintainer: John Prybylski jprybylski@gmail.com (ORCID) [copyright holder]
Authors:
John Prybylski jprybylski@gmail.com (ORCID) [copyright holder]
See Also
Useful links:
Pipe operator
Description
See magrittr::%>% for details.
Usage
lhs %>% rhs
Arguments
lhs |
A value or the magrittr placeholder. |
rhs |
A function call using the magrittr semantics. |
Value
The result of calling rhs(lhs).
Binary check if LHS is parent of RHS
Description
Binary check if LHS is parent of RHS
Usage
possible_parent %p% possible_child
Arguments
possible_parent |
< |
possible_child |
... < |
Value
<logical> TRUE if LHS is parent of RHS
Examples
# Detect direct parent
pheno_set$run6 %p% pheno_set$run7
# Detect non-parentage (does not try to "flip" parentage)
pheno_set$run6 %p% pheno_set$run5
# Does not detect grand-parentage
pheno_set$run6 %p% pheno_set$run13
Describe parameter/covariate associations
Description
The relationship between a structural parameter and a covariate can be
described, so that the covariate's effect on that parameter – and the
uncertainty of that effect – can later be visualized with
xplot_forest() (via prm_cov()/prm_contcov()/prm_catcov()).
This is deliberately parallel to add_prm_association(): the same
formula-based declaration style, the same two-stage
check-then-process validation, and the same "redeclare to replace"
upsert behavior. It is a separate mechanism (own storage, own getters)
because a covariate association needs more shape than an omega
association – a covariate column, a required reference value, and
(for categorical covariates or custom()) more than one theta – and
it produces a range of effect sizes rather than a single scalar CV.
Usage
add_cov_association(xpdb, ..., .problem, .subprob, .method, quiet)
drop_cov_association(xpdb, ..., .problem, .subprob, .method, quiet)
Arguments
xpdb |
< |
... |
< For |
.problem |
< |
.subprob |
< |
.method |
< |
quiet |
Silence extra output. |
Details
Format for associations is:
LHS ~ fun(COVARIATE, THETA..., ref = ..., ...)
LHS: Selector for a fixed-effect (theta) parameter, exactly as in
add_prm_association()(the{m},{name}or{label}, unquoted). Multiple parameters can share one association with+(eg, a covariate that affects bothCLandQthrough the same theta).RHS
COVARIATE: The first (positional) argument. The bare, unquoted name of acontcov/catcovcolumn (seexpose::xp_var()) – not a fixed-effect or omega selector.RHS
THETA...: One or more further positional arguments, selecting the fixed-effect parameter(s) that carry the covariate effect magnitude (same selector rules as LHS –the{m}/{name}/{label}, unquoted). How many are expected depends onfun; see the built-in list below.RHS
ref: Required, named, no default, for every association regardless offun. This is the covariate value (for continuous covariates) or raw level (for categorical covariates) that the effect is normalized against – the point at which the reported effect ratio is exactly1. There is no way to safely infer this from thexpdbalone (NONMEM control streams commonly normalize a covariate against a hardcoded constant baked into the code, which is invisible toxpose), so it must always be stated explicitly, the same wayadd_prm_association()'snmboxcoxrequires an explicitlambda.
All built-ins express the covariate's effect as a multiplicative
effect_ratio on the parameter's typical value, and are constructed so
that effect_ratio == 1 whenever the covariate equals ref,
regardless of the theta value. Available built-ins:
-
linear(COV, THETA, ref=):1 + \theta (COV - ref) -
power(COV, THETA, ref=):(COV / ref)^\theta(allometric) -
exponential(COV, THETA, ref=):e^{\theta (COV - ref)} -
additive(COV, THETA, ref=):(\theta + COV) / (\theta + ref). An uncommon but simple form where the covariate is added directly (with an implicit coefficient of1, unlikelinear's explicit slope) to an intercept-likeTHETA, egCL = THETA(n) + WTin the underlying model. -
hockey(COV, THETA_LO, THETA_HI, ref=, brk=ref): PsN's "hockey-stick" two-slope piecewise-linear model –1 + \theta_{lo} (COV - ref)whenCOV <= brk,1 + \theta_{hi} (COV - ref)whenCOV > brk.brk(the breakpoint) defaults toref(PsN's usual default: breakpoint = normalization reference), but can be given separately, eg for a covariate normalized to its observed median while the clinically meaningful cutpoint is a round number (ref = 90, brk = 60for an eGFR-like covariate). -
catshift(COV, THETA..., ref=): One theta per non-reference raw level of a categorical covariate,effect_ratio = 1 + THETA_ifor leveli(1atref). Assumes the typical NONMEM pattern of one theta per non-reference category (egIF (RACE.EQ.2) CLCOV = THETA(9)). Thetas are matched to non-reference levels in ascending raw-value order – if that order is ambiguous or wrong for a given model, usecustom()instead.
For anything else, custom(COV, THETA..., ref=, fun=) is the escape
hatch: fun is a function of (cov, ref, theta) (theta is always a
numeric vector, even when only one THETA selector is given) returning
the effect ratio. Because custom() can't be verified by
construction the way the built-ins can, add_cov_association()
validates it at declaration time by evaluating fun(ref, ref, theta)
for a few probe values of theta (not the currently-fitted value,
which could coincidentally pass while fun is still wrong for other
theta values) and requires each to equal 1; if it doesn't, the error
states the required invariant and shows what fun actually returned,
rather than failing silently or only much later during plotting.
A note on parameter/theta scale
The computed effect ratio never touches the LHS parameter's own fitted
value – only the covariate-effect theta(s), the covariate value, and
ref – so it does not matter whether the LHS was itself parameterized
on a log, logit, or identity scale in the control stream (get_prm()'s
transform argument only affects diagonal OMEGA/SIGMA reporting
(variance -> SD, covariance -> correlation); THETA values are always
the raw fitted estimate regardless of transform, so there is nothing
to reconcile there either).
What is assumed is that the chosen association – a builtin or
custom() – is an exact match for the functional form actually used
in the model code, including any scale factor baked into that code
(eg a covariate effect entered as THETA(n)*(COV-ref)/100). There is
no way to verify this from the xpdb alone; if a builtin's literal
formula (see above) doesn't match the real model, the result will be
a numerically valid but silently wrong effect ratio, not an error –
the same caveat add_prm_association() already carries for CV%
calculation.
If the covariate-effect theta itself is not already on the scale a
builtin expects (eg it was fitted on a logit or other transformed
scale, or needs some other rescaling to match one of the literal
formulas above), transform it back with mutate_prm() before
declaring the association – the same recommended workflow as
add_prm_association()'s own untransformed-theta requirement.
Value
An updated xp_xtras object
See Also
add_prm_association(), prm_cov(), mutate_prm()
Examples
# xpdb_x's THETA7 ("CRCL on CL") is a genuine covariate effect already
# in the model, so this is a faithful (if allometric-flavored, for
# illustration) description of it:
xpdb_x %>%
add_cov_association(TVCL ~ power(CLCR, THETA7, ref = 64)) %>%
prm_cov()
# hockey-stick (PsN-style): different slope above/below the reference
xpdb_x %>%
add_cov_association(TVCL ~ hockey(CLCR, THETA7, THETA4, ref = 64)) %>%
prm_cov()
# Categorical: one theta per non-reference level. SEX has 2 levels
# (1, 2), so catshift needs exactly one theta for the non-reference
# level; THETA4 is reused here purely for illustration.
xpdb_x %>%
add_cov_association(TVCL ~ catshift(SEX, THETA4, ref = 1)) %>%
prm_cov()
# custom(): fun(cov, ref, theta) must equal 1 when cov == ref
xpdb_x %>%
add_cov_association(
TVCL ~ custom(CLCR, THETA7, ref = 64,
fun = function(cov, ref, theta) (cov/ref)^theta)
) %>%
prm_cov()
# Dropping an association is easy
bad_assoc <- xpdb_x %>%
add_cov_association(TVCL ~ power(CLCR, THETA7, ref = 64))
bad_assoc %>%
drop_cov_association(TVCL ~ CLCR) %>%
prm_cov()
Describe parameter associations
Description
The relationship between structural parameters and omega parameters can be described. This is useful if it deviates from the typical log-normal.
Default transformations are those that are built into
pmxcv, but see examples for how associations can be
described for other relationships.
Note: When these associations are used to calculate CV%, it is assumed
that the value for the theta parameter is untransformed. So, if a parameter is
fitted in the logit scale, the value should be transformed back to normal scale
with mutate_prm() (eg, mutate_prm(the~plogis) before declaring the~logit(ome).
Usage
add_prm_association(xpdb, ..., .problem, .subprob, .method, quiet)
drop_prm_association(xpdb, ..., .problem, .subprob, .method, quiet)
Arguments
xpdb |
< |
... |
... < For |
.problem |
< |
.subprob |
< |
.method |
< |
quiet |
Silence extra output. |
Details
At time of writing, the built-in distributions for pmxcv are below.
Those marked with an asterisk require a fixed effect parameter to calculate CV.
-
logtypical log-normal. Optionalexactparameter (ifTRUE, default, will not calculate with integration); this is unrelated to thecvtypeoption. Note, ifcvtypeoption is set to"sqrt", log-normalget_prmCVs will use the square root, not any integration or analytical estimate, regardless of how this association is specified. -
logexp* modified log-normallog(1+X) -
logit* logit-normal -
arcsin* arcsine-transform -
nmboxcox* Box-Cox transform as typically implemented in pharmacometrics. Requires alambdaparameter.
To pass a custom parameter, use custom transform, and pass pdist and qdist to
that transform. See Examples.
Reminder about qdist and pdist: Consider that qlogis transforms a proportion
to a continuous, unbounded number; it is the logit transform. The plogis function
converts a continuous, unbounded number to a proportion; it is the inverse logit
transform. Other R stats functions work similarly, and as such functions used as
qdist and pdist values are expected to act similarly.
Note that the functions used in describing associations are not real functions,
it is just the syntax for this application. Based on examples, be mindful of
where positional arguments would acceptable and where named arguments are
required. Care has been given to provide a modest amount of flexibility
with informative errors for fragile points, but not every error can be anticipated.
If this function or downstream results from it seem wrong, the association syntax
should be scrutinized. These "functions" are not processed like in mutate_prm,
so (eg) the2 will not be substituted for the value of the2; if
lambda is a fitted value (like the2), in that edge case the value of the2 should be written
explicitly in the association formula, and if any mutate_prm changes the2 then users
should be mindful of the new association needed. This may be updated in the future.
Format for associations is:
LHS~fun(OMEGA, args...)
LHS: Selector for a fixed effect parameter. Can be
the{m}(eg, the1),{name}(eg, THETA1) or{label}(eg, TVCL). These should not be quoted. Multiple associations can be defined at once with+. Cannot be empty.RHS: Should be a simple call to only one function, which should be custom or one of the built-in distributions or
custom(...). A lot of things can look like simple calls, so may not break immediately; keep to the described format and everything should be fine.RHS OMEGA: Selector for omega variable. Similar rules to the fixed effect selector. Can be
ome{m},{name}or{label}, limited to diagonal elements. Should not be quoted.OMEGAis not a named argument (OMEGA={selector}should not be considered valid); whatever is used as the first argument to the "function" will be considered an OMEGA selector. NOTE, if selecting an OMEGA parameter by name (eg,OMEGA(2,2)), backticks (eg`OMEGA(2,2)`) must be used or else the selection will throw an error.RHS args: Applies when the distribution has extra arguments. If these are limited to 1, can be passed by position (eg,
lambdafornmboxcoxandexactforlog). Forcustom(),qdist,pdistand any arguments needed to pass to them should be named.
For the nmboxcox transformation, a lambda value (especially negative ones) may
not work well with the integration-based CV estimation. This may occur even if
the lambda is fitted and stable in that fitting, but it cannot be predicted which
ones will be affected. This note is intended to forewarn that this might happen.
Value
An updated xp_xtras object
References
Prybylski, J.P. Reporting Coefficient of Variation for Logit, Box-Cox and Other Non-log-normal Parameters. Clin Pharmacokinet 63, 133-135 (2024). doi:10.1007/s40262-023-01343-2
See Also
Examples
pheno_base %>%
add_prm_association(the1~log(IIVCL),V~log(IIVV)) %>%
get_prm() # get_prm is the only way to see the effect of associations
# These values are not fitted as logit-normal, but
# just to illustrate:
pheno_final %>%
add_prm_association(the1~logit(IIVCL),Vpkg~logit(IIVV)) %>%
get_prm()
# ... same for Box-Cox
pheno_base %>%
add_prm_association(V~nmboxcox(IIVV, lambda=0.5)) %>%
# Naming the argument is optional
add_prm_association(CL~nmboxcox(IIVCL, -0.1)) %>%
get_prm()
# A 'custom' use-case is when logexp, log(1+X), is
# desired but 1 is too large.
# Again, for this example, treating this like it applies here.
pheno_base %>%
add_prm_association(V~custom(IIVV, qdist=function(x) log(0.001+x),
pdist=function(x) exp(x)-0.001)) %>%
get_prm()
# Dropping association is easy
bad_assoc <- pheno_final %>%
add_prm_association(the1~logit(IIVCL),Vpkg~logit(IIVV))
bad_assoc %>% get_prm()
bad_assoc %>%
drop_prm_association(the1) %>%
get_prm()
Add, apply, list, amend or remove xpdb processing presets
Description
A "process preset" is a one-sided formula (using .x for the
incoming xpdb, as in a purrr-style lambda) or a plain function that
bundles up a repeated processing pipeline – e.g. converting to
xp_xtras, dropping unused ETAs, assigning labels/levels – so it can
be re-applied with process_preset() instead of being retyped for every
model.
add_process_preset() stores a preset in the current session (by name,
or an auto-incrementing integer if name isn't given).
process_preset() applies a stored preset to an xpdb.
print_process_preset() lists stored presets. remove_process_preset()
deletes one. amend_process_preset() replaces an existing preset's
definition in place.
Usage
add_process_preset(
preset,
name = NULL,
overwrite = FALSE,
persist = FALSE,
ask = TRUE,
profile = "project"
)
process_preset(xpdb, preset, ...)
print_process_preset(name = NULL)
remove_process_preset(name, persist = FALSE, ask = TRUE, profile = "project")
amend_process_preset(
name,
preset,
persist = FALSE,
ask = TRUE,
profile = "project"
)
Arguments
preset |
< |
name |
< |
overwrite |
< |
persist |
< |
ask |
< |
profile |
< |
xpdb |
< |
... |
For |
Value
add_process_preset()/amend_process_preset()/
remove_process_preset() return the (character(1)) preset name,
invisibly. process_preset() returns the processed xpdb.
print_process_preset() returns the printed presets (a named list),
invisibly.
Persistence and CRAN policy
By default, presets are session-only: they vanish when R restarts. Set
persist = TRUE to additionally write the current set of presets to a
.Rprofile so they're recreated automatically in future sessions.
Per CRAN policy, a package must not write to files outside
tempdir() without the user's explicit, interactive consent, and never
as a side effect of a non-interactive process (R CMD check, tests,
vignette builds, Rscript, ...). Accordingly, persist = TRUE:
only ever writes when
rlang::is_interactive()isTRUE– it errors otherwise, so it is always a no-op underR CMD check/testthat/knitr– andasks for confirmation (via
utils::askYesNo()) before writing, unlessask = FALSEis passed explicitly by the (already-interactive) caller.
The target file defaults to a project-scoped .Rprofile (in
getwd()), which only affects R sessions started in that directory;
pass profile = "user" to instead target the user-level profile
(Sys.getenv("R_PROFILE_USER"), falling back to ~/.Rprofile), or any
string to use it as a literal file path. Presets are written as a single
marked block (bounded by # >>> xpose.xtras process presets ... >>> /
# <<< ... <<<) so re-syncing replaces the whole block rather than
accumulating duplicate calls, and the block is removed entirely once the
last preset is deleted. Persisted presets must be self-contained –
since they're recreated from deparsed source on each new session, they
cannot depend on transient local variables from the session that
created them.
Formula presets and .x vs .
Use .x (not a bare .) as the placeholder for the incoming xpdb in a
formula preset, e.g. ~ .x %>% as_xpdb_x() %>% set_var_type(...). A
leading . immediately before %>% is itself magrittr syntax for
building a reusable function (see ?magrittr::`%>%`): ~ . %>% f()
would silently return a function instead of applying it, since the
formula's own . placeholder collides with magrittr's.
See Also
Examples
add_process_preset(
~ .x %>% as_xpdb_x() %>% set_var_types(na = any_of(paste0("ETA", 5:9))),
name = "drop_higher_etas"
)
print_process_preset()
xpdb_ex_pk_processed <- xpose::xpdb_ex_pk %>%
process_preset("drop_higher_etas")
amend_process_preset(
"drop_higher_etas",
~ .x %>% as_xpdb_x() %>% set_var_types(na = any_of(paste0("ETA", 7:9)))
)
remove_process_preset("drop_higher_etas")
Add relationship(s) to an xpose_set
Description
Add relationship(s) to an xpose_set
Usage
add_relationship(xpdb_s, ..., .warn = TRUE, .remove = FALSE)
remove_relationship(xpdb_s, ...)
Arguments
xpdb_s |
< |
... |
< |
.warn |
< |
.remove |
< |
Value
An xpose_set object with relationships added
Examples
xpdb_set %>%
add_relationship(mod1~fix2) # ouroboros
xpdb_set %>%
remove_relationship(fix1~mod2) # split down the middle
Add a watermark to a plot
Description
Overlays large, semi-transparent, rotated text across a ggplot or
xpose_plot object (e.g. "DRAFT", "PRELIMINARY", "CONFIDENTIAL").
Calling it directly always adds a watermark (falling back to the
built-in defaults below if nothing else is configured). It is also
applied automatically by print.xpose_plot() and
ggsave_xp() whenever a default_watermark is actually configured
(see the auto_apply entry in set_xtras_options()) – unlike this
function, that automatic trigger never invents an unconfigured
watermark on its own.
label/colour/alpha/size/angle/fontface resolve with the same
precedence as apply_default_labs(): (in increasing precedence) the
xpose.xtras.default_watermark R option, xpdb-level defaults set via
set_default_watermark() (when xpdb is supplied), then the argument
itself when explicitly passed. Built-in fallbacks ("DRAFT",
"grey50", 0.3, 24, 30, "bold") apply if a setting isn't
resolved from any of those.
Usage
add_watermark(plot, label, colour, alpha, size, angle, fontface, xpdb = NULL)
Arguments
plot |
< |
label |
< |
colour |
< |
alpha |
< |
size |
< |
angle |
< |
fontface |
< |
xpdb |
< |
Value
plot, with the watermark layer added
See Also
set_xtras_options() for the full list of xpose.xtras.*
session options, and get_xtras_option() to check which tier
(option/xpdb) is currently dominant for a given xpdb.
Examples
p <- xpose::dv_vs_ipred(xpose::xpdb_ex_pk)
add_watermark(p, label = "PRELIMINARY")
options(xpose.xtras.default_watermark = list(label = "CONFIDENTIAL", colour = "red"))
add_watermark(p)
options(xpose.xtras.default_watermark = NULL)
Add one or more xpdb objects to an xpose_set
Description
Add one or more xpdb objects to an xpose_set
Usage
add_xpdb(xpdb_s, ..., .relationships = NULL)
Arguments
xpdb_s |
< |
... |
< |
.relationships |
< |
Value
An xpose_set object with the new xpdb objects added
Examples
data("xpdb_ex_pk", package = "xpose")
add_xpdb(xpdb_set, ttt=xpdb_ex_pk)
Apply default label overrides to a plot
Description
Resolves title/subtitle/caption/tag labels for plot from (in
increasing precedence):
the
xpose.xtras.default_labsR option (a named list, see examples),defaults set on
xpdbviaset_default_labs(), whenxpdbis supplied (a rendered plot does not retain enough of its sourcexpdbto look this up automatically – pass it explicitly),values passed directly via
....
By default only labels not already set on the plot are filled in; set
overwrite = TRUE to replace existing labels too.
print.xpose_plot() calls this automatically
whenever xpose.xtras.auto_apply is enabled (the default; see
set_xtras_options()), but apply_default_labs() itself is a
standalone function that doesn't depend on that print method existing,
so it works the same regardless of whether that method survives issue
#36's eventual removal.
Usage
apply_default_labs(plot, ..., xpdb = NULL, overwrite = FALSE)
Arguments
plot |
< |
... |
< |
xpdb |
< |
overwrite |
< |
Value
plot, with resolved labels applied
See Also
set_xtras_options() for the full list of xpose.xtras.*
session options, and get_xtras_option() to check which tier
(option/xpdb) is currently dominant for a given xpdb.
Examples
options(xpose.xtras.default_labs = list(caption = "Draft -- do not distribute"))
p <- xpose::dv_vs_ipred(xpose::xpdb_ex_pk)
apply_default_labs(p)
options(xpose.xtras.default_labs = NULL)
Level-defining helper functions
Description
Level-defining helper functions
Usage
as_leveler(x, .start_index = 1, .ordered = FALSE)
is_leveler(x)
lvl_bin(x = c("No", "Yes"), .start_index = 0)
lvl_sex()
lvl_inord(x, .start_index = 1, .ordered = TRUE)
Arguments
x |
< |
.start_index |
< |
.ordered |
< |
Value
Special character vector suitable to be used as leveler
Examples
set_var_levels(xpdb_x,
SEX = lvl_sex(),
MED1 = lvl_bin(),
MED2 = lvl_inord(c("n","y"), .start_index = 0)
)
Convert an object to an xpose_data and xp_xtras object
Description
This function masks the default in xpose package, adding the
xp_xtras class to default xpose_data objects.
Usage
as_xpdb_x(x)
as_xp_xtras(x)
check_xpdb_x(x, .warn = TRUE)
check_xp_xtras(...)
Arguments
x |
Suspected |
.warn |
< |
... |
Forwarded |
Value
<xpose_data> and <xp_xtras> object
Examples
xp_x <- as_xpdb_x(xpose::xpdb_ex_pk)
check_xpdb_x(xp_x)
Attach nlmixr2 fit object to xpose data object
Description
Attach nlmixr2 fit object to xpose data object
Usage
attach_nlmixr2(xpdb, obj)
Arguments
xpdb |
< |
obj |
< |
Value
An object of the same class as xpdb with an additional element.
Examples
## Not run:
# Based on an example from nlmixr2 documentation
xpdb_nlmixr2 <- nlmixr_example("xpdb_nlmixr2")
one.cmt <- function() {
ini({
tka <- 0.45 # Ka
tcl <- log(c(0, 2.7, 100)) # Log Cl
tv <- 3.45; label("log V")
eta.ka ~ 0.6
eta.cl ~ 0.3
eta.v ~ 0.1
add.sd <- 0.7
})
model({
ka <- exp(tka + eta.ka)
cl <- exp(tcl + eta.cl)
v <- exp(tv + eta.v)
linCmt() ~ add(add.sd)
})
}
theo_sd_fit <- nlmixr2::nlmixr2(one.cmt, nlmixr2data::theo_sd,
"focei", control = nlmixr2::foceiControl(print = 0))
attach_nlmixr2(
xpdb_nlmixr2, theo_sd_fit
) %>%
as_xpdb_x() %>%
print() # fit will be mentioned in print() method
## End(Not run)
Add individual objective function to data
Description
Add individual objective function to data
Usage
backfill_iofv(xpdb, .problem = NULL, .subprob = NULL, .label = "iOFV")
Arguments
xpdb |
< |
.problem |
Problem number |
.subprob |
Subproblem number |
.label |
The name of the new column. |
Details
This function will only work for objects with software listed as
nonmem or nlmixr2. For nonmem, the object should haves a phi
file and with an OBJ column in that file. For nlmixr2, the fit
object data should have individual observation likelihoods in a column
called NLMIXRLLIKOBS (this is a current standard, but is checked at runtime).
Value
<xp_xtras> object with new column in the data and a
column with iofv var type.
Examples
xpdb_x %>%
backfill_iofv() %>%
list_vars()
Populate some properties from nlmixr2 fit
Description
Populate some properties from nlmixr2 fit
Usage
backfill_nlmixr2_props(xpdb)
Arguments
xpdb |
< |
Details
This function will currently backfill:
condn
nsig
Examples
## Not run:
xpdb_nlmixr2 <- nlmixr_example("xpdb_nlmixr2")
xpdb_nlmixr2 %>%
set_prop(condn = "not implemented") %>%
get_prop("condn")
xpdb_nlmixr2 %>%
set_prop(condn = "not implemented") %>%
backfill_nlmixr2_props() %>%
get_prop("condn")
## End(Not run)
Non-simulation based likelihood model diagnostic
Description
These plots attempt to provide a means of verifying that the estimated likelihoods and probabilities for categorical outcomes are captured within the model.
When the smooth spline is included (type includes "s"), it is
expected that the overall trend is up and to the right; a relatively
flat trend suggests that the modeled likelihood is inconsistent with the
observed outcome.
Usage
catdv_vs_dvprobs(
xpdb,
mapping = NULL,
cutpoint = 1,
type = "vbs",
title = "@y vs. @x | @run",
subtitle = "Ofv: @ofv, Number of individuals: @nind",
caption = "@dir",
tag = NULL,
xlab = c("probability", "basic"),
facets,
.problem,
quiet,
...
)
Arguments
xpdb |
< |
mapping |
|
cutpoint |
< |
type |
See Details. |
title |
Plot title |
subtitle |
Plot subtitle |
caption |
Plot caption |
tag |
Plot tag |
xlab |
Either use the typical basic x-axis label (the cutpoint-defined column name) or label it based on the probability/likelihood it is estimating. |
facets |
Additional facets |
.problem |
Problem number |
quiet |
Silence extra debugging output |
... |
Any additional aesthetics. |
Details
For type-based customization of plots:
-
bbox-whisker (using default quantiles) -
ppoints (fromgeom_dotplot) -
vviolin (fromgeom_violin) -
ooutliers (show outliers) -
lline through 0 (or as indicated inhline_yinterceptoryline_xintercept) -
ssmooth line (fromgeom_smooth) -
jjitter points (fromgeom_jitter) -
cconnecting lines for jitter points (fromgeom_path)
Value
The desired plot
Examples
# Test M3 model
pkpd_m3 %>%
# Need to ensure var types are set
set_var_types(catdv=BLQ,dvprobs=LIKE) %>%
# Set probs
set_dv_probs(1, 1~LIKE, .dv_var = BLQ) %>%
# Optional, but useful to set levels
set_var_levels(1, BLQ = lvl_bin()) %>%
# Plot with basic xlab makes no assumptions
catdv_vs_dvprobs(xlab = "basic")
# Test categorical model
vismo_xpdb <- vismo_pomod %>%
set_var_types(.problem=1, catdv=DV, dvprobs=matches("^P\\d+$")) %>%
set_dv_probs(.problem=1, 0~P0,1~P1,ge(2)~P23)
# Various cutpoints (note axes labels and texts)
vismo_xpdb %>%
catdv_vs_dvprobs(xlab = "basic")
vismo_xpdb %>%
catdv_vs_dvprobs(cutpoint = 2, xlab = "basic")
vismo_xpdb %>%
catdv_vs_dvprobs(cutpoint = 3, xlab = "basic")
# Latter is arguably clearer with default xlab
vismo_xpdb %>%
catdv_vs_dvprobs(cutpoint = 3)
Binned calibration plot for categorical DVs
Description
A binned alternative to catdv_vs_dvprobs(). The probability column
associated with cutpoint is split into bins equally-sized groups,
from lowest to highest predicted probability, and for each bin the
observed proportion of the categorical DV meeting the cutpoint
condition is calculated (i.e. the m/M observations in that bin with
the target value).
For a well-specified model, the mean predicted probability of a bin
should be close to the bin's observed proportion, so plotted points
are expected to fall around the unity (y = x) line.
Usage
catdv_vs_ipred(
xpdb,
mapping = NULL,
cutpoint = 1,
bins = 10,
type = "pl",
guide = TRUE,
title = "Observed frequency vs. predicted probability | @run",
subtitle = "Ofv: @ofv, Number of individuals: @nind",
caption = "@dir",
tag = NULL,
xlab = c("probability", "basic"),
facets,
.problem,
quiet,
...
)
Arguments
xpdb |
< |
mapping |
|
cutpoint |
< |
bins |
< |
type |
String setting the type of plot to be used: line |
guide |
Include the unity ( |
title |
Plot title |
subtitle |
Plot subtitle |
caption |
Plot caption |
tag |
Plot tag |
xlab |
Either use the typical basic x-axis label (the cutpoint-defined column name) or label it based on the probability/likelihood it is estimating. |
facets |
Additional facets |
.problem |
Problem number |
quiet |
Silence extra debugging output |
... |
Any additional aesthetics. |
Value
The desired plot
See Also
Examples
# Test M3 model
pkpd_m3 %>%
# Need to ensure var types are set
set_var_types(catdv=BLQ,dvprobs=LIKE) %>%
# Set probs
set_dv_probs(1, 1~LIKE, .dv_var = BLQ) %>%
# Optional, but useful to set levels
set_var_levels(1, BLQ = lvl_bin()) %>%
# Plot with 5 bins
catdv_vs_ipred(bins = 5)
# Test categorical model
vismo_xpdb <- vismo_pomod %>%
set_var_types(.problem=1, catdv=DV, dvprobs=matches("^P\\d+$")) %>%
set_dv_probs(.problem=1, 0~P0,1~P1,ge(2)~P23)
# Various cutpoints and bin counts
vismo_xpdb %>%
catdv_vs_ipred(bins = 8, xlab = "basic")
vismo_xpdb %>%
catdv_vs_ipred(cutpoint = 2, bins = 8, xlab = "basic")
vismo_xpdb %>%
catdv_vs_ipred(cutpoint = 3, bins = 8, xlab = "basic")
Longitudinal binned observed vs. predicted plot for categorical DVs
Description
A longitudinal alternative to catdv_vs_ipred() and to xpose's own
xpose::dv_preds_vs_idv() for categorical outcomes. Rather than binning
by predicted probability (as catdv_vs_ipred() does) or plotting raw
per-subject values against a continuous independent variable, this bins
observations by a discrete, typically ordered grouping variable (eg an
occ-typed occasion column) and plots the observed proportion meeting
the cutpoint condition alongside the mean predicted probability, one
point/line per bin.
Usage
catdv_vs_occ(
xpdb,
mapping = NULL,
bin = NULL,
cutpoint = 1,
type = "pl",
title = "Observed and predicted probability vs. @x | @run",
subtitle = "Ofv: @ofv, Number of individuals: @nind",
caption = "@dir",
tag = NULL,
facets,
.problem,
quiet,
...
)
Arguments
xpdb |
< |
mapping |
|
bin |
< |
cutpoint |
< |
type |
String setting the type of plot to be used: point |
title |
Plot title |
subtitle |
Plot subtitle |
caption |
Plot caption |
tag |
Plot tag |
facets |
Additional facets |
.problem |
Problem number |
quiet |
Silence extra debugging output |
... |
Any additional aesthetics. |
Value
The desired plot
See Also
catdv_vs_ipred(), catdv_vs_dvprobs()
Examples
# Derive an occasion column (TIME is in hours here) and level it in
# visit order
vismo_xpdb <- vismo_pomod %>%
set_var_types(.problem = 1, catdv = DV, dvprobs = matches("^P\\d+$")) %>%
set_dv_probs(.problem = 1, 0~P0, 1~P1, ge(2)~P23) %>%
xpose::mutate(OCC = ceiling((TIME + 1) / 24), .problem = 1) %>%
set_var_types(.problem = 1, occ = OCC) %>%
set_var_levels(.problem = 1, OCC = lvl_inord(paste("Day", 1:12)))
vismo_xpdb %>%
catdv_vs_occ()
vismo_xpdb %>%
catdv_vs_occ(cutpoint = 3)
Verify validity of level list
Description
Verify validity of level list
Usage
check_levels(lvl_list, index, .ordered = character())
Arguments
lvl_list |
< |
index |
Index of |
.ordered |
< |
Value
Nothing, warning or error
Check an xpose_set object
Description
Check an xpose_set object
Usage
check_xpose_set(xpdb_s, .warn = TRUE)
check_xpose_set_item(xpdb_s_i, .example = xpdb_set)
Arguments
xpdb_s |
< |
.warn |
< |
xpdb_s_i |
< |
.example |
< |
Value
TRUE or error thrown
Examples
check_xpose_set(xpdb_set)
check_xpose_set_item(xpdb_set$mod1)
Calculate all binary confusion matrix indices
Description
Calculate all binary confusion matrix indices
Usage
confmatr_by_threshold(
test_vec,
true_vec,
...,
threshold = 0.5,
pos_val = 1,
prepend = "",
cols = dplyr::everything()
)
Arguments
test_vec |
< |
true_vec |
< |
... |
For future extension |
threshold |
< |
pos_val |
< |
prepend |
< |
Value
dataframe of confusion matrix indices
Parameter correlation/covariance matrix heatmap
Description
Visualizes the parameter correlation (or covariance) matrix as a heatmap,
filling a gap left behind in translation from xpose4. Values come from
get_cov_matrix(), which has built-in support for nonmem and
nlmixr2 models; rendering is done with the generic xplot_heatmap()
template.
Usage
cormat(
xpdb,
type = c("correlation", "covariance"),
.problem = NULL,
.subprob = NULL,
.method = NULL,
drop_fixed = TRUE,
digits,
title,
subtitle = "Ofv: @ofv, Condition number: @condn",
caption = "@dir",
tag = NULL,
quiet,
...
)
Arguments
xpdb |
< |
type |
< |
.problem |
< |
.subprob |
< |
.method |
< |
drop_fixed |
< |
digits |
Number of significant digits to display in cell labels. Defaults to |
title |
Plot title |
subtitle |
Plot subtitle |
caption |
Plot caption |
tag |
Plot tag |
quiet |
Silence extra debugging output |
... |
Additional aesthetics, passed to |
Details
Only the upper triangle of the matrix is drawn, as it is symmetric.
Fixed-effect (theta) and random-effect (omega/sigma) parameters are
both included for nonmem models, when available and not fixed. For
nlmixr2 models, only fixed effects are included, as nlmixr2 does not
report uncertainty for random effects. See get_cov_matrix() for
further details on availability; if the covariance step was not run, or
did not complete successfully, an informative error is raised.
Value
The desired plot
Examples
cormat(xpdb_x)
cormat(xpdb_x, type = "covariance")
Covariate effect forest plot
Description
Visualizes the effect of covariates on structural parameters, as
declared with add_cov_association(), as a forest plot: one row per
(parameter, covariate, evaluation point), the point estimate and
interval as a ratio to the parameter's typical value, with a reference
line at 1.
This is the covariate-specific wrapper: it calls prm_cov() to
compute the effect-size table and xplot_forest() (a generic,
forest-plot-agnostic renderer, see its own documentation) to draw it.
Usage
cov_forest(
xpdb,
...,
type = "pilr",
region = NULL,
show_ref = TRUE,
log = TRUE,
forest_opts = list(),
title = "Covariate effects on model parameters | @run",
subtitle = "Ratio to typical parameter value; reference line at 1",
caption = "@dir",
tag = NULL,
.problem = NULL,
.subprob = NULL,
.method = NULL,
quiet
)
Arguments
xpdb |
< |
... |
< |
type |
Passed to |
region |
< |
show_ref |
< |
log |
< |
forest_opts |
< |
title |
Plot title |
subtitle |
Plot subtitle |
caption |
Plot caption |
tag |
Plot tag |
.problem |
< |
.subprob |
< |
.method |
< |
quiet |
Silence extra output |
Value
The desired plot
See Also
add_cov_association(), prm_cov(), xplot_forest()
Examples
xpdb_x %>%
add_cov_association(
TVCL ~ power(CLCR, THETA7, ref = 64),
TVCL ~ catshift(SEX, THETA4, ref = 1)
) %>%
cov_forest()
Derive full parameter set for mammillary PK model
Description
This function applies rxode2::rxDerived to model parameters.
Usage
derive_prm(
xpdb,
.prm = NULL,
.problem,
quiet = xpdb$options$quiet,
prefix = ""
)
backfill_derived(
xpdb,
.prm = NULL,
.problem,
quiet = xpdb$options$quiet,
...,
group_vars = "id"
)
Arguments
xpdb |
xpdb < |
.prm |
< |
.problem |
Optional. Problem to use. |
quiet |
Optional. Extra output. |
prefix |
If desired, apply prefix to new parameters. |
... |
Passed to |
group_vars |
Variable type(s) to join derived parameters on. |
Value
<data.frame> of data with new parameters
Examples
## Not run:
nlmixr2_m3 <- nlmixr_example("nlmixr2_m3")
nlmixr2_m3 %>%
backfill_derived() %>%
list_vars()
derive_prm(nlmixr2_m3)
# If param has no vars, .prm should be set
pheno_base %>%
backfill_derived(
.prm = c(CL,V)
) %>%
list_vars()
## End(Not run)
Backfill utility for descriptions
Description
A slightly more generic approach to getting model descriptions.
Usage
desc_from_comments(
xpdb,
start_check = ".*description",
maxlines = 5,
remove = paste0(start_check, ":\\s*"),
extra_proc = c,
collapse = " "
)
Arguments
xpdb |
< |
start_check |
Regular expression used to mark start of description. This is tested case-insensitively. |
maxlines |
If the number of lines after description to the first code block is more than 1, this allows a limit. |
remove |
By default, the start check and a colon, with optional whitespace. A regex. |
extra_proc |
Any extra processing that might be desired prior to collapsing the description lines. This should be a vectorized function. |
collapse |
Character to use when collapsing multiple lines. |
Value
The description-updated <xpose_data) object
See Also
Examples
# This has a description, but it's not visible by default
pheno_base
# It can be added with the following
pheno_base %>%
desc_from_comments()
# Extra processing for preference can also implemented
pheno_base %>%
desc_from_comments(extra_proc = tolower)
# If a run label ($PROB) would make a good description, use the
# following instead:
pkpd_m3 %>%
set_prop(descr=get_prop(pkpd_m3,"label"))
Check for potential parameterization issues
Description
This function can help diagnose potential flip-flop or other issues related to the parameterization of the model.
Usage
diagnose_constants(
xpdb,
df = NULL,
micro_pattern = "^K(\\d+|EL?)$",
vol_pattern = "^V(C|D|1|2|)$",
fo_abs = "KA",
fo_rates = c("alpha_beta", "lambda", "custom"),
checks = list(flip_flop = NULL, neg_microvol = NULL, units_match = NULL),
df_units = NULL,
.problem,
quiet = xpdb$options$quiet
)
Arguments
xpdb |
< |
df |
Optional < |
micro_pattern |
Regex. Pattern for microconstants |
vol_pattern |
Regex. Pattern for volume parameter (should only match 1) |
fo_abs |
First-order absorption parameter (singular, fixed, not regex). |
fo_rates |
Derived ("macro") exponential rate constants (fixed). See Details |
checks |
See Details |
df_units |
Named list of units. If |
.problem |
Used in fetching parameters. |
quiet |
Should parameter fetching produce output? |
Details
The function prints output directly, not as an object.
A finding from these checks does not necessarily prove the parameterization is erroneous (indeed, flip-flop PK can exist), but coupled with other findings would help in diagnosing issues.
For fo_rates, "alpha_beta" and "lambda" are convenience placeholders
meaning literally c("ALPHA","BETA","GAMMA") and paste0("LAMBA",1:3),
respectively. If capitalization or competing names will be an issue, specify
a custom set of names (provide a character vector of names, do not pass
"custom" to the argument). If only a subset of alpha_beta or lambda
are available, but these are the parameterizations used (eg, only ALPHA)
these options can still be used. If LAMBDA is used alone, it will not
match the "lambda" default. If naming conventions are incompatible, it
is suggested xpdb or df be subject to mutation or renaming to use this
function.
The available checks at this time are:
-
flip_flopChecks iffo_absare slower than the derivedfo_rates. -
neg_microvolChecks if any microconstant or volume is negative. Note this check applies to parameterization of microconstants, so only a single volume (parameterizations with multiple volumes do not use microconstants) should matchvol_pattern. -
units_matchFor any checks, verifies units are consistent. This check requires units are defined byset_var_units()ordf_unitsfor parameters applicable to a requested check.
Checks must be requested as a named list of these elements, either TRUE or
FALSE (truth determines if the test is done). If the default NULL is used,
test will be run if the required parameters are present.
Value
Nothing
See Also
Examples
## Not run:
nlmixr2_m3 <- nlmixr_example("nlmixr2_m3")
nlmixr2_m3 %>%
backfill_derived() %>%
diagnose_constants(vol_pattern = "^V$")
nlmixr2_m3 %>%
backfill_derived() %>%
diagnose_constants(
vol_pattern = "^V$",
df_units = list(KA = "1/hr", ALPHA = "1/hr"),
checks = list(neg_microvol = FALSE)
)
# Using df form
derive_prm(nlmixr2_m3) %>%
diagnose_constants(df = ., vol_pattern = "^V$")
## End(Not run)
Visualize xpose_set
Description
In its current state, this function is intended to
provide a simple visual representation of an xpose_set.
Functionality and aesthetic enhancements are expected in
future releases.
Usage
diagram_lineage(xpdb_s, ...)
Arguments
xpdb_s |
< |
... |
For later expansion. Will be ignored. |
Value
A DiagrammeR-compliant graph object.
Examples
## Not run:
diagram_lineage(pheno_set) %>%
DiagrammeR::render_graph(layout="tree")
## End(Not run)
Display deltaOFV values across xpose_set
Description
If no base model is provided, and if lineage is unclear,
the first model in the xpose_set is used as the base model.
Usage
## S3 method for class 'xpose_set'
diff(x, ...)
Arguments
x |
< |
... |
< |
Value
<numeric> vector of deltaOFV values
Check if any xpose_data objects are repeated in xpose_set
Description
Check if any xpose_data objects are repeated in xpose_set
Usage
## S3 method for class 'xpose_set'
duplicated(x, incomparables = FALSE, ...)
Arguments
x |
< |
incomparables |
|
... |
Must be empty |
Value
A logical vector or list of logical vectors
Model average plots
Description
This is for use when the model averaging of a set is planned.
Usage
dv_vs_ipred_modavg(
xpdb_s,
...,
.lineage = FALSE,
algorithm = c("maa", "msa"),
weight_type = c("individual", "population"),
auto_backfill = FALSE,
weight_basis = c("ofv", "aic", "res"),
res_col = "RES",
quiet
)
dv_vs_pred_modavg(
xpdb_s,
...,
.lineage = FALSE,
algorithm = c("maa", "msa"),
weight_type = c("individual", "population"),
auto_backfill = FALSE,
weight_basis = c("ofv", "aic", "res"),
res_col = "RES",
quiet
)
ipred_vs_idv_modavg(
xpdb_s,
...,
.lineage = FALSE,
algorithm = c("maa", "msa"),
weight_type = c("individual", "population"),
auto_backfill = FALSE,
weight_basis = c("ofv", "aic", "res"),
res_col = "RES",
quiet
)
pred_vs_idv_modavg(
xpdb_s,
...,
.lineage = FALSE,
algorithm = c("maa", "msa"),
weight_type = c("individual", "population"),
auto_backfill = FALSE,
weight_basis = c("ofv", "aic", "res"),
res_col = "RES",
quiet
)
plotfun_modavg(
xpdb_s,
...,
.lineage = FALSE,
avg_cols = NULL,
avg_by_type = NULL,
algorithm = c("maa", "msa"),
weight_type = c("individual", "population"),
auto_backfill = FALSE,
weight_basis = c("ofv", "aic", "res"),
res_col = "RES",
.fun = NULL,
.funargs = list(),
quiet
)
Arguments
xpdb_s |
< |
... |
< |
.lineage |
< |
algorithm |
< |
weight_type |
< |
auto_backfill |
< |
weight_basis |
< |
res_col |
< |
quiet |
< |
avg_cols |
< |
avg_by_type |
< |
.fun |
< |
.funargs |
< |
Value
The desired plot
See Also
Examples
pheno_set %>%
dv_vs_ipred_modavg(run8,run9,run10, auto_backfill = TRUE)
pheno_set %>%
dv_vs_pred_modavg(run8,run9,run10, auto_backfill = TRUE)
pheno_set %>%
ipred_vs_idv_modavg(run8,run9,run10, auto_backfill = TRUE)
pheno_set %>%
pred_vs_idv_modavg(run8,run9,run10, auto_backfill = TRUE)
# Model averaged ETA covariates
pheno_set %>%
plotfun_modavg(run8,run9,run10, auto_backfill = TRUE,
avg_by_type = "eta",.fun = eta_vs_catcov,
# Note quoting
.funargs = list(etavar=quote(ETA1)))
Master xpdb editing function
Description
Generic function used to build dedicated editing functions
Usage
edit_xpose_data(
.fun,
.fname,
.data,
...,
.problem,
.source,
.where,
check_quos = FALSE
)
Arguments
.fun |
An editing function to be applied to the data. |
.fname |
The name of the editing function. |
.data |
An xpose database object. |
... |
Name-value pairs of expressions. Use |
.problem |
The problem from which the data will be modified |
.source |
The source of the data in the xpdb. Can either be 'data' or an output file extension e.g. 'phi'. |
.where |
A vector of element names to be edited in special (e.g.
|
check_quos |
Check that variables referenced exists. These arguments are automatically quoted and evaluated in the context of the data frame. They support unquoting and splicing. See the dplyr vignette("programming") for an introduction to these concepts. |
Value
The modified xpose_data object
Grid plots
Description
This is essentially a wrapper around ggpairs,
except it uses xpose motifs and styling. Note that this function
produces a lot of repetitive output if quiet=FALSE; this may not
be an issue, but it could look like an error has occurred if many covariates
and individual parameter estimates are included.
Usage
eta_grid(
xpdb,
mapping = NULL,
etavar = NULL,
drop_fixed = TRUE,
title = "Eta correlations | @run",
subtitle = "Based on @nind individuals, Eta shrink: @etashk",
caption = "@dir",
tag = NULL,
pairs_opts,
.problem,
quiet,
...
)
cov_grid(
xpdb,
mapping = NULL,
cols = NULL,
covtypes = c("cont", "cat"),
show_n = TRUE,
drop_fixed = TRUE,
title = "Covariate relationships | @run",
subtitle = "Based on @nind individuals",
caption = "@dir",
tag = NULL,
pairs_opts,
.problem,
quiet,
...
)
eta_vs_cov_grid(
xpdb,
mapping = NULL,
etavar = NULL,
cols = NULL,
covtypes = c("cont", "cat"),
show_n = TRUE,
drop_fixed = TRUE,
title = "Eta covariate correlations | @run",
subtitle = "Based on @nind individuals, Eta shrink: @etashk",
caption = "@dir",
tag = NULL,
etacov = TRUE,
pairs_opts,
.problem,
quiet,
...
)
Arguments
xpdb |
< |
mapping |
|
etavar |
|
drop_fixed |
As in |
title |
Plot title |
subtitle |
Plot subtitle |
caption |
Plot caption |
tag |
Plot tag |
pairs_opts |
List of arguments to pass to |
.problem |
Problem number |
quiet |
Silence extra debugging output |
... |
Passed to |
cols |
|
covtypes |
Subset to specific covariate type? |
show_n |
Count the number of |
etacov |
For |
Value
xp_tras_plot object
Examples
eta_grid(xpdb_x)
cov_grid(xpdb_x)
eta_vs_cov_grid(xpdb_x)
# Labels and units are also supported
xpdb_x %>%
xpose::set_var_labels(AGE="Age", MED1 = "Digoxin") %>%
xpose::set_var_units(AGE="yrs") %>%
set_var_levels(SEX=lvl_sex(), MED1 = lvl_bin()) %>%
eta_vs_cov_grid()
Eta categorical covariate plots (typical)
Description
Eta categorical covariate plots (typical)
Usage
eta_vs_catcov(
xpdb,
mapping = NULL,
etavar = NULL,
drop_fixed = TRUE,
orientation = "x",
show_n = check_xpdb_x(xpdb, .warn = FALSE),
type = "bol",
title = "Eta versus categorical covariates | @run",
subtitle = "Based on @nind individuals, Eta shrink: @etashk",
caption = "@dir",
tag = NULL,
facets,
.problem,
quiet,
...
)
Arguments
xpdb |
< |
mapping |
|
etavar |
|
drop_fixed |
As in |
orientation |
Passed to |
show_n |
Add "N=" to plot |
type |
Passed to |
title |
Plot title |
subtitle |
Plot subtitle |
caption |
Plot caption |
tag |
Plot tag |
facets |
Additional facets |
.problem |
Problem number |
quiet |
Silence output |
... |
Any additional aesthetics. |
Details
The ability to show number per covariate level is inspired
by the package pmplots, but is implements here within
the xpose ecosystem for consistency.
Value
The desired plot
Examples
eta_vs_catcov(xpdb_x)
# Labels and units are also supported
xpdb_x %>%
xpose::set_var_labels(AGE="Age", MED1 = "Digoxin") %>%
xpose::set_var_units(AGE="yrs") %>%
set_var_levels(SEX=lvl_sex(), MED1 = lvl_bin()) %>%
eta_vs_catcov()
Eta continuous covariate plots (typical)
Description
Eta continuous covariate plots (typical)
Usage
eta_vs_contcov(
xpdb,
mapping = NULL,
etavar = NULL,
drop_fixed = TRUE,
linsm = FALSE,
type = "ps",
title = "Eta versus continuous covariates | @run",
subtitle = "Based on @nind individuals, Eta shrink: @etashk",
caption = "@dir",
tag = NULL,
log = NULL,
guide = TRUE,
facets,
.problem,
quiet,
...
)
Arguments
xpdb |
< |
mapping |
|
etavar |
|
drop_fixed |
As in |
linsm |
If |
type |
Passed to |
title |
Plot title |
subtitle |
Plot subtitle |
caption |
Plot caption |
tag |
Plot tag |
log |
Log scale covariate value? |
guide |
Add guide line? |
facets |
Additional facets |
.problem |
Problem number |
quiet |
Silence output |
... |
Any additional aesthetics. |
Value
The desired plot
Examples
eta_vs_contcov(xpdb_x)
# Labels and units are also supported
xpdb_x %>%
xpose::set_var_labels(AGE="Age", MED1 = "Digoxin") %>%
xpose::set_var_units(AGE="yrs") %>%
set_var_levels(SEX=lvl_sex(), MED1 = lvl_bin()) %>%
eta_vs_contcov()
Expose a model parameter of xpdb objects in an xpose_set
Description
Expose a model parameter of xpdb objects in an xpose_set
Usage
expose_param(xpdb_s, ..., .problem = NULL, .subprob = NULL, .method = NULL)
Arguments
xpdb_s |
< |
... |
< |
.problem |
< |
.subprob |
< |
.method |
< |
Details
The parameter returned will be top-level, and to avoid conflicting
names will be prepended by .. (e.g., ..ome1). The selector
used to fetch the parameter will be used in this .. name. If
a better name is preferred, there are convenient renaming functions
from dplyr where needed.
When using parameter selectors, quotations should be used for more
complex names, like "OMEGA(1,1)", since these may be read incorrectly
otherwise.
The untransformed parameter is used for this exposure. The get_prm
call uses transform=FALSE.
Value
An xpose_set object with the parameter exposed
See Also
Examples
pheno_set %>%
expose_param(the1) %>%
reshape_set()
pheno_set %>%
expose_param(RUVADD, "OMEGA(1,1)") %>%
reshape_set()
# This function is useful for generating a model-building table
pheno_set %>%
# Determine longest lineage
select(all_of(xset_lineage(.))) %>%
# Select key variability parameters
expose_param(RUVADD, "OMEGA(1,1)") %>%
# Make sure all models have descriptions
focus_qapply(desc_from_comments) %>%
# Extract description
expose_property(descr) %>%
# Transform to tibble
reshape_set() # %>% pipe into other processing
Expose a property of xpdb objects in an xpose_set
Description
Expose a property of xpdb objects in an xpose_set
Usage
expose_property(xpdb_s, ..., .problem = NULL, .subprob = NULL, .method = NULL)
Arguments
xpdb_s |
< |
... |
< |
.problem |
< |
.subprob |
< |
.method |
< |
Details
The property returned will be top-level, and to avoid conflicting
names will be prepended by .. (e.g., ..descr).
For some properties, transformations are applied automatically to make them more useful. This includes:
-
etashkandepsshk: transformed to numeric vectors as in <get_shk> -
ofvand other per-problem properties: transformed as needed and pulls from eachxpdbdefault problem.
Value
An xpose_set object with the properties exposed
See Also
Examples
xpdb_set <- expose_property(xpdb_set, descr)
xpdb_set$mod1$..descr
xpdb_set <- expose_property(xpdb_set, etashk)
xpdb_set$mod1$..etashk
Place .problem, .subprob and .method into environment consistently
Description
Since this is a common need, it is being functionalized to ensure consistency.
Usage
fill_prob_subprob_method(
xpdb,
.problem,
.subprob,
.method,
envir = parent.frame(),
for_summary = FALSE
)
Arguments
xpdb |
< |
.problem |
|
.subprob |
|
.method |
|
envir |
< |
for_summary |
< |
Filtration method for xpose_set
Description
Filtration method for xpose_set
Usage
## S3 method for class 'xpose_set'
filter(.data, ..., .rowwise = FALSE)
Arguments
.data |
< |
... |
< |
.rowwise |
< |
Value
A filtered xpose_set
Examples
xpdb_set %>%
filter(label=="mod1")
xpdb_set %>%
filter(length(parent)>1, .rowwise=TRUE)
Focus on an xpdb object in an xpose_set
Description
For piping, set is passed, but with S3 method transformations are applied to the focused xpdb object.
Usage
focus_xpdb(xpdb_s, ..., .add = FALSE)
unfocus_xpdb(xpdb_s)
focused_xpdbs(xpdb_s)
focus_function(xpdb_s, fn, ...)
focus_qapply(xpdb_s, fn, ..., .mods = everything())
Arguments
xpdb_s |
< |
... |
< |
.add |
< |
fn |
< |
.mods |
< |
Details
While these functions are used internally, it is recognized that they may have value in user scripting. It is hoped these are self-explanatory, but the examples should address common uses.
Note: focus_qapply() (re)focuses as specified in .mods and then un-focuses all elements
of the set so should only be used in the case where a quick application
suffices. Otherwise, focusing with a sequence of focus_function calls
(or a monolithic single focus_function call with a custom function)
should be preferred.
focus_function()/focus_qapply() support two kinds of fn:
-
Transform functions, which take an
xpose_data/xp_xtrasobject and return one (e.g.set_var_types_x). These are applied to each focused element in place, and the (still-focused)xpose_setis returned so calls can keep being piped. -
Output-generating functions, which take an
xpose_data/xp_xtrasobject but return something else (e.g. a plot or table). These are applied to each focused element, and the raw output is returned instead of anxpose_set: a single value if only one element is focused, or a named list (by label) of outputs if several are focused.
Value
An xpose_set object with the focused xpdb object(s) transformed in place, or,
for functions that do not return an xpose_data/xp_xtras object, the output of fn
(or a named list of outputs, if multiple elements are focused)
Examples
# Select two xpdb objects to focus on
xpdb_set %>% focus_xpdb(mod2,fix1)
# Add a focus
xpdb_set %>% focus_xpdb(mod2,fix1) %>% focus_xpdb(mod1, .add=TRUE)
# Remove focus
xpdb_set %>% focus_xpdb(mod2,fix1) %>% focus_xpdb()
## Not run:
# Focus function and tidyselect
pheno_set %>%
focus_xpdb(everything()) %>%
# Add iOFV col and iofv type to all xpdbs in set
focus_function(backfill_iofv) %>%
# Show 1... can do all like this, too, but no need
unfocus_xpdb() %>%
select(run6) %>%
{.[[1]]$xpdb} %>%
list_vars()
# Quick-apply version of previous example
pheno_set %>%
focus_qapply(backfill_iofv) %>%
select(run6) %>%
{.[[1]]$xpdb} %>%
list_vars()
## End(Not run)
# Output-generating function applied to a single focused element:
# returns the plot itself, not an xpose_set
pheno_set %>%
focus_xpdb(run6) %>%
focus_function(xpose::dv_vs_ipred)
# ... or with several elements focused, a named list of plots
pheno_set %>%
focus_xpdb(run6, run7) %>%
focus_function(xpose::dv_vs_ipred)
Combine a property from all components of a franken_xpdb
Description
Combine a property from all components of a franken_xpdb
Usage
franken_prop(
xpdb_f,
xpdb_list,
prop,
problem = NULL,
glue_cmd = function(x) glue::glue_collapse(x, ", ", last = " and "),
indices = seq_along(xpdb_list)
)
Arguments
xpdb_f |
A product of |
xpdb_list |
List of the source |
prop |
< |
problem |
< |
glue_cmd |
Any special transformation to the properties, including how to collapse. |
indices |
< |
Details
This function is meant to be called within franken_xpdb.
It is expected to be ready to handle cases where, for example,
multiple props are being set in a pipe, or a problem-associated
property is being set while a problem=0 property is also being
set.
This is a low-level function, so its use outside of internal functions is not intended.
Value
Same as xpdb_f with new properties.
Examples
# This is designed to be called in a function environment which
# would provide something like the following:
xpdb_f <- franken_xpdb(pheno_base, pheno_final, .types="catcov")
xpdb_list <- list(pheno_base, pheno_final)
# The following would be inside the function
xpdb_f %>%
franken_prop(xpdb_list, "run",
glue_cmd = function(x) paste(x, collapse="+"))
# xpdb_f may have to be written to a few times if
# and problem-specific combinations are needed:
updated <- xpdb_f %>%
franken_prop(xpdb_list, "run",
glue_cmd = function(x) paste(x, collapse="+"))
# problem will also be available. Assume there's
# no reason to loop here, but that may be needed
problem <- 1
updated <- updated %>%
franken_prop(xpdb_list, "ofv", problem=problem,
glue_cmd = function(x) paste(x, collapse="&"))
Combine several xpose_data objects into one
Description
This is an internal function designed to meet the needs of specific plotting functions
Usage
franken_xpdb(
...,
.cols = NULL,
.types = NULL,
prop_transforms = NULL,
problem,
quiet = TRUE
)
Arguments
... |
< |
.cols |
< |
.types |
< |
prop_transforms |
< |
problem |
< |
quiet |
Prevents extra output. |
Value
The first xpose_data object with new data columns
Examples
franken_xpdb(pheno_base, pheno_final, .types="catcov") %>%
xpose::get_data() %>%
select(starts_with("APGR"))
Extract a parameter covariance or correlation matrix
Description
Pulls the uncertainty (covariance step) matrix for estimated parameters,
with built-in support for nonmem (via the .cov/.cor output tables)
and nlmixr2 (via the fit object's covariance matrix) models. This is
what feeds cormat(), but is exported separately since it may be
useful on its own (eg, for programmatic checks on parameter colinearity).
Usage
get_cov_matrix(
xpdb,
type = c("correlation", "covariance"),
.problem = NULL,
.subprob = NULL,
.method = NULL,
drop_fixed = TRUE,
quiet
)
Arguments
xpdb |
< |
type |
< |
.problem |
< |
.subprob |
< |
.method |
< |
drop_fixed |
< |
quiet |
< |
Details
For nonmem models, the matrix is built from the .cor/.cov output
tables produced by the $COV step. NONMEM includes fixed-effect
parameters in these tables as placeholder zeros (since no uncertainty is
estimated for them); drop_fixed (the default) removes them.
For nlmixr2 models, uncertainty is only calculated for fixed-effect
(theta) parameters; nlmixr2 does not report standard errors, and
therefore no covariance/correlation, for random-effect (omega)
elements. drop_fixed has no effect here, since parameters without a
standard error are already excluded from the fit's covariance matrix.
In both cases, if the covariance step was not run, or did not complete successfully, an informative error is raised rather than returning partial or placeholder data.
Value
A symmetric numeric matrix, with parameter names as dimnames.
Examples
get_cov_matrix(xpdb_x)
get_cov_matrix(xpdb_x, type = "covariance")
## Not run:
xpdb_nlmixr2 <- nlmixr_example("xpdb_nlmixr2")
get_cov_matrix(xpdb_nlmixr2)
## End(Not run)
Get full index for xpose_data data
Description
Get full index for xpose_data data
Usage
get_index(xpdb, .problem = NULL, ...)
set_index(xpdb, index, ...)
Arguments
xpdb |
< |
.problem |
< |
... |
Ignored. Here for future expansion |
index |
< |
Value
Tibble of index
Examples
get_index(xpose::xpdb_ex_pk)
Access model parameters
Description
Access model parameter estimates from an xpdb object.
Methods have been added to implement extensions. See Details.
Usage
get_prm(
xpdb,
.problem = NULL,
.subprob = NULL,
.method = NULL,
digits = 4,
transform = TRUE,
show_all = FALSE,
quiet
)
Arguments
xpdb |
An |
.problem |
The problem to be used, by default returns the last one for each file. |
.subprob |
The subproblem to be used, by default returns the last one for each file. |
.method |
The estimation method to be used, by default returns the last one for each file |
digits |
The number of significant digits to be displayed. |
transform |
Should diagonal OMEGA and SIGMA elements be transformed to standard deviation and off diagonal elements be transformed to correlations. |
show_all |
Logical, whether the 0 fixed off-diagonal elements should be removed from the output. |
quiet |
Logical, if |
Details
When using an <xp_xtra> object, this function will add a column to the output
where CV% for each diagonal element of omega is calculated. This CV% is with
respect to the resulting structural parameter, so unless the default log-normal
association is applicable update with add_prm_association.
For log-normal, users may prefer to use the first-order CV% (\sqrt{\omega^2})
instead of the exact. In such case, xpdb <- set_option(xpdb, cvtype="sqrt") will
get that preferred form.
If a single omega parameter is associated with multiple fixed effect parameters,
the cv column will be a list. For the omega row associated with multiple
fixed effect parameters, there will be multiple CV values. This will be the case
even if the transformation is log-normal and therefore scale-invariant, given
the need for generality.
Note the approach used to calculate CV% assumes an untransformed scale for the
fitted parameter value (unrelated to transform=TRUE). That means, for example,
that for a logit-normal fitted parameter value, it is expected the value will be
something constrained between 0 and 1, not the unbounded, continuous transformed value.
The function <mutate_prm> is intended to help where that might be an issue.
Value
A tibble for single problem/subprob or a named list for multiple problem|subprob.
References
Prybylski, J.P. Reporting Coefficient of Variation for Logit, Box-Cox and Other Non-log-normal Parameters. Clin Pharmacokinet 63, 133-135 (2024). doi:10.1007/s40262-023-01343-2
See Also
Examples
# xpose parameter table
get_prm(xpose::xpdb_ex_pk, .problem = 1)
# xpose.xtra parameter table (basically the same)
get_prm(pheno_final, .problem = 1)
# For the sake of example, even though these were all lognormal:
pheno_final %>%
add_prm_association(CLpkg~logit(IIVCL)) %>%
add_prm_association(Vpkg~nmboxcox(IIVV, lambda = 0.01)) %>%
get_prm(.problem = 1)
get_prm equivalent for nlmixr2 fits
Description
This is intended to match the <xpose::get_prm> rather than the
updated get_prm().
Usage
get_prm_nlmixr2(
xpdb,
transform = formals(get_prm)$transform,
show_all = formals(get_prm)$show_all,
quiet = FALSE
)
Arguments
xpdb |
< |
transform |
< |
show_all |
< |
quiet |
< |
Value
a tibble with expected columns
Generic function to extract a property from a model summary
Description
Generic function to extract a property from a model summary
Usage
get_prop(
xpdb,
prop,
.problem = NULL,
.subprob = NULL,
.method = NULL,
.tail = 1
)
Arguments
xpdb |
< |
prop |
< |
.problem |
< |
.subprob |
< |
.method |
< |
.tail |
< |
Value
Exact value for the property
Examples
data("xpdb_ex_pk", package = "xpose")
get_prop(xpdb_ex_pk, "descr")
Get shrinkage estimates from model summary
Description
This function parses shrinkages as they are currently
presented in get_summary, so it
is dependent on the current implementation of that function.
Usage
get_shk(xpdb, wh = "eta", .problem = NULL, .subprob = NULL, .method = NULL)
Arguments
xpdb |
An |
wh |
The shrinkage to extract ( |
.problem |
Problem number to use. Uses the xpose default if not provided. |
.subprob |
< |
.method |
< |
Value
A numeric vector of shrinkage estimates.
Examples
data("xpdb_ex_pk", package = "xpose")
# eta Shrinkage
get_shk(xpdb_ex_pk)
# epsilon Shrinkage
get_shk(xpdb_ex_pk, wh = "eps")
Inspect which xpose.xtras option value is dominant
Description
For the two "two-tier" options – default_labs and
default_watermark, which can be set both as a session-wide R option
(via set_xtras_options()) and per-xpdb (via set_default_labs() /
set_default_watermark()) – reports the value at each tier and which
one is dominant, i.e. would currently be used by apply_default_labs()
/ add_watermark() absent any argument passed directly to those
functions (which always takes precedence over both tiers).
The other options recognized by set_xtras_options() (save_dir,
save_width, save_height, gg_theme, xp_theme) have no xpdb-level
tier to compare against (see the Details in set_xtras_options()), so
for those xpdb is always NULL and dominant is "option" or
"neither".
Usage
get_xtras_option(name, xpdb = NULL)
Arguments
name |
< |
xpdb |
< |
Value
a list with elements option (the getOption() value),
xpdb (the xpdb-level value, or NULL), and dominant (one of
"option", "xpdb", or "neither")
Examples
options(xpose.xtras.default_labs = list(caption = "session default"))
xpdb_x2 <- set_default_labs(xpdb_x, caption = "model-specific")
get_xtras_option("default_labs", xpdb_x2)
options(xpose.xtras.default_labs = NULL)
Save a plot with xpose.xtras default output resolution
Description
A ggplot2::ggsave()-compatible wrapper (defaulting to
ggplot2::ggsave() itself, but swappable via save_fun – e.g. for
reportifyr::ggsave_with_metadata() or any other function sharing
ggsave()'s plot/filename/path/width/height signature).
Before saving: resolved labels are applied via apply_default_labs()
and a configured watermark (if any) via add_watermark() – see
apply_labs/apply_watermark, both of which default to the
xpose.xtras.auto_apply option (TRUE unless changed), the same
switch print.xpose_plot() uses, so a plot looks the
same whether it's viewed interactively or saved with ggsave_xp().
filename/path have any @keyword placeholders expanded via
xpose::parse_title(), the same way xpose::xpose_save() does
(independent of which save_fun is used, since most save functions
don't do this themselves); and path/width/height/save_fun fall
back to the xpose.xtras.save_dir, xpose.xtras.save_width,
xpose.xtras.save_height, and xpose.xtras.save_fun R options when not
supplied explicitly, so a project can set output defaults once (see
set_xtras_options()).
Usage
ggsave_xp(
plot = ggplot2::last_plot(),
filename,
path = getOption("xpose.xtras.save_dir"),
width = getOption("xpose.xtras.save_width", 7),
height = getOption("xpose.xtras.save_height", 6),
xpdb = NULL,
apply_labs = getOption("xpose.xtras.auto_apply", TRUE),
apply_watermark = getOption("xpose.xtras.auto_apply", TRUE),
save_fun = getOption("xpose.xtras.save_fun", ggplot2::ggsave),
...
)
Arguments
plot |
< |
filename |
< |
path |
< |
width, height |
< |
xpdb |
< |
apply_labs |
< |
apply_watermark |
< |
save_fun |
< |
... |
Passed on to |
Value
the result of save_fun (for the default ggplot2::ggsave(),
the saved file path, invisibly)
See Also
set_xtras_options() for the full list of xpose.xtras.*
session options.
Examples
## Not run:
options(xpose.xtras.save_dir = "figures", xpose.xtras.save_width = 8)
p <- xpose::dv_vs_ipred(xpose::xpdb_ex_pk)
ggsave_xp(p, filename = "dv_vs_ipred.png")
## End(Not run)
Grab processed xpose_plot
Description
This function is very simple and unlikely to capture every possible situation. Paginated plots are not supported.
This is helpful for working with xpose plots in patchwork or
ggpubr functions.
Usage
grab_xpose_plot(plot)
Arguments
plot |
< |
Value
Grob or list of grobs
Examples
single_plot <- xpdb_x %>%
eta_vs_catcov(etavar = ETA1) %>%
grab_xpose_plot()
listof_plots <- xpdb_x %>%
eta_vs_catcov(etavar = c(ETA1,ETA3)) %>%
grab_xpose_plot()
Individual plots for a (stratified) sample of individuals
Description
A wrapper around ind_plots that first draws a
sample of n individuals (9 by default, enough to fill a 3x3 page)
rather than plotting every individual in the dataset. If stratify is
provided, the sample is drawn proportionally from each level (or
combination of levels) of the tidyselect-ed column(s), so the sample
remains as representative as the data and n allow.
Usage
ind_plots_sample(
xpdb,
n = 9,
stratify = NULL,
seed = NULL,
facets,
.problem,
quiet,
...
)
Arguments
xpdb |
< |
n |
< |
stratify |
< |
seed |
< |
facets |
As in |
.problem |
< |
quiet |
< |
... |
Passed on to |
Details
When stratify is used, the stratifying column(s) are appended to the
facet formula (in addition to the id column that ind_plots
already facets by), so that the stratum each sampled individual belongs
to is visible in the plot.
Stratified sample sizes are allocated proportionally to stratum size
using the largest-remainder method, so the total sampled always equals
min(n, sum(individuals available across all strata)).
Value
The desired plot
See Also
Examples
xpdb_x %>% ind_plots_sample(n = 6)
xpdb_x %>% ind_plots_sample(n = 6, stratify = SEX)
Individual ROC plots
Description
To identify any individual likelihood predictions that may be more influential or unusual.
Note this function may have a long runtime.
Usage
ind_roc(
xpdb,
mapping = NULL,
cutpoint = 1,
type = "ca",
title = "Individual ROC curves | @run",
subtitle = "Ofv: @ofv, Eps shrink: @epsshk",
caption = "@dir | Page @page of @lastpage",
tag = NULL,
facets,
.problem,
quiet,
...
)
Arguments
xpdb |
< |
mapping |
|
cutpoint |
< |
type |
See Details. |
title |
Plot title |
subtitle |
Plot subtitle |
caption |
Plot caption |
tag |
Plot tag |
facets |
Additional facets |
.problem |
Problem number |
quiet |
Silence extra debugging output |
... |
Any additional aesthetics. |
Details
For type-based customization of plots:
-
cROC curve (usinggeom_path) -
kKey points on ROC curve (where on curve the threshold isthres_fixed) (usinggeom_point) -
pROC space points (usinggeom_point) -
tROC space text (usinggeom_text) -
aAUC in bottom right (usinggeom_label)
Value
The desired plot
Examples
## Not run:
vismo_pomod %>%
set_var_types(.problem=1, catdv=DV, dvprobs=matches("^P\\d+$")) %>%
set_dv_probs(.problem=1, 0~P0,1~P1,ge(2)~P23) %>%
ind_roc()
## End(Not run)
Objective function changes across models
Description
Another visualization of how individual objective functions change over the course of model development.
Usage
iofv_vs_mod(
xpdb_s,
...,
.lineage = FALSE,
auto_backfill = FALSE,
mapping = NULL,
orientation = "x",
type = "bjc",
title = "Individual Ofvs across models",
subtitle = "Based on @nind individuals, Initial Ofv: @ofv",
caption = "Initial @dir",
tag = NULL,
axis.text = "@run",
facets,
.problem,
quiet
)
Arguments
xpdb_s |
< |
... |
< |
.lineage |
< |
auto_backfill |
< |
mapping |
|
orientation |
Defaults to |
type |
Passed to < |
title |
Plot title |
subtitle |
Plot subtitle |
caption |
Plot caption |
tag |
Plot tag |
axis.text |
What to label the model. This is parsed on a per-model basis. |
facets |
Additional facets |
.problem |
Problem number |
quiet |
Silence output |
Value
The desired plot
Examples
pheno_set %>%
focus_qapply(backfill_iofv) %>%
iofv_vs_mod()
pheno_set %>%
focus_qapply(backfill_iofv) %>%
iofv_vs_mod(run3,run11,run14,run15)
pheno_set %>%
focus_qapply(backfill_iofv) %>%
iofv_vs_mod(.lineage = TRUE)
Compare model predictions
Description
For two models in an xpose_set, these functions are useful in comparing individual
and population predictions
Usage
ipred_vs_ipred(
xpdb_s,
...,
.inorder = FALSE,
type = "pls",
title = "Individual prediction comparison | @run",
subtitle = "Ofv: @ofv, Eps shrink: @epsshk",
caption = "@dir",
tag = NULL,
log = NULL,
guide = TRUE,
axis.text = "@run",
facets,
.problem,
quiet
)
pred_vs_pred(
xpdb_s,
...,
.inorder = FALSE,
type = "pls",
title = "Population prediction comparison | @run",
subtitle = "Ofv: @ofv, Eps shrink: @epsshk",
caption = "@dir",
tag = NULL,
log = NULL,
guide = TRUE,
axis.text = "@run",
facets,
.problem,
quiet
)
Arguments
xpdb_s |
< |
... |
See < |
.inorder |
See < |
type |
Passed to |
title |
Plot title |
subtitle |
Plot subtitle |
caption |
Plot caption |
tag |
Plot tag |
log |
Log scale covariate value? |
guide |
Add guide line? |
axis.text |
What to show in the axes to distinguish the model values |
facets |
Additional facets |
.problem |
Problem number |
quiet |
Silence output |
Value
The desired plot
Examples
pheno_set %>%
ipred_vs_ipred(run5,run15)
pheno_set %>%
pred_vs_pred(run5,run15)
Add simulation counter
Description
Because this has been fixed in the parent package, the fix will be removed in an upcoming release.
Add a column containing a simulation counter (irep). A new simulation is counted every time a value in x is different than its previous value and is a duplicate.
This version of the function does not require IDs be ascending, but does not work for
datasets where IDs are repeated (not in sequence). Both cases are read as separate
individuals for NONMEM, but NONMEM does not need to detect repetition of ID sequences (for NONMEM,
1,1,2,2,3,3,1,1,2,2,3,3 is 6 individuals, regardless of being 2 repeats of 3 individuals).
Given the vast majority of datasets use 1 individual per ID, (which cannot be said about IDs
always being ascending), only one of these corrections is implemented.
Usage
irep(x, quiet = FALSE)
Arguments
x |
The column to be used for computing simulation number, usually the ID column. |
quiet |
Logical, if |
Details
Bugfix for irep.
Value
<numeric> vector tracking the number of simulations based on unique subject IDs.
Examples
data("xpdb_ex_pk", package = "xpose")
xpdb_ex_pk_2 <- xpdb_ex_pk %>%
mutate(sim_id = irep(ID), .problem = 2)
Convenience functions used in package
Description
Convenience functions used in package
Usage
is_formula_list(x)
Arguments
x |
object to test |
Value
<logical> TRUE if is a list of formulas
Is this a model-averaged/combined ("franken") xpose_data object?
Description
Is this a model-averaged/combined ("franken") xpose_data object?
Usage
is_franken_xpdb(xpdb)
Arguments
xpdb |
< |
Value
<logical>
Basic class checker for xp_xtras
Description
Basic class checker for xp_xtras
Usage
is_xp_xtras(x)
Arguments
x |
Object to test |
Value
<logical> TRUE if xp_xtras object
Examples
is_xp_xtras(xpose::xpdb_ex_pk)
is_xp_xtras(xpdb_x)
Left join, backfilling shared columns instead of duplicating them
Description
As <dplyr::left_join>, but any column present in both x and y
(besides the join keys) is coalesced instead of suffixed: values already
present in x are kept, and only missing (NA) values are filled in from
y.
Usage
join_backfill(
x,
y,
by = NULL,
copy = FALSE,
suffix = c(".x", ".y"),
...,
keep = NULL
)
Arguments
x |
An |
y |
A data frame (or another object coercible to one) to join in. |
by |
Join specification, as in < |
copy |
If |
suffix |
Suffixes used internally to disambiguate a column shared by |
... |
Other parameters passed onto < |
keep |
Passed to < |
Value
A data frame
Backfill missing variables via a left join
Description
<dplyr::left_join> wrapper for xpose_data (and, by inheritance,
xp_xtras) objects. Unlike a plain left_join(), a column present in
both x and y (other than the join keys) is not duplicated with
.x/.y suffixes: missing (NA) values already in x are backfilled
from the matching value in y, while non-missing values already in x
are left untouched. This makes it straightforward to backfill a variable
(or set of variables) that is only partially recorded, from a second data
source keyed on the same join variable(s) (e.g. ID).
left_join_x() accepts xpose_data/xp_xtras objects directly, with an
additional .problem argument restricting which problem(s) the join is
applied to.
left_join() without _x is defined as an S3 method on xpose_data, so
that the usual <dplyr::left_join> generic dispatches here
automatically (xp_xtras objects are handled the same way, via class
inheritance).
Usage
left_join_x(
x,
y,
by = NULL,
copy = FALSE,
suffix = c(".x", ".y"),
...,
keep = NULL,
.problem = NULL
)
## S3 method for class 'xpose_data'
left_join(
x,
y,
by = NULL,
copy = FALSE,
suffix = c(".x", ".y"),
...,
keep = NULL,
.problem = NULL
)
Arguments
x |
An |
y |
A data frame (or another object coercible to one) to join in. |
by |
Join specification, as in < |
copy |
If |
suffix |
Suffixes used internally to disambiguate a column shared by |
... |
Other parameters passed onto < |
keep |
Passed to < |
.problem |
The problem number(s) to which the join will be applied. Uses all problems if |
Value
An updated xpose_data/xp_xtras object.
Examples
# Some subjects are missing an APGR score in the base dataset
xpdb_missing <- pheno_base %>%
mutate_x(APGR = dplyr::if_else(ID %in% c("1", "2"), NA, APGR))
# A separate table with the (complete) values, keyed on ID
apgr_lookup <- xpose::get_data(pheno_base, quiet = TRUE) %>%
dplyr::distinct(ID, APGR)
# Existing APGR values are kept; only the missing ones are filled in
left_join_x(xpdb_missing, apgr_lookup, by = "ID")
For a categorical DV variable, show associated probabilities
Description
A convenient quick check for how probabilities are currently
assigned, based on set_dv_probs.
Usage
list_dv_probs(xpdb, .problem = NULL, .dv_var = NULL)
Arguments
xpdb |
< |
.problem |
< |
.dv_var |
< |
Value
<tibble> of probabilities
Examples
pkpd_m3 %>%
set_dv_probs(1, 1~LIKE, .dv_var = BLQ) %>%
list_dv_probs(.dv_var=BLQ)
Updates to list_vars
Description
To accommodate changes made in xpose.xtras,
<list_vars> needed some minimal updates.
Usage
list_vars(xpdb, .problem = NULL, ...)
## Default S3 method:
list_vars(xpdb, .problem = NULL, ...)
## S3 method for class 'xp_xtras'
list_vars(xpdb, .problem = NULL, ...)
Arguments
xpdb |
< |
.problem |
< |
... |
Should be blank. |
Value
<tibble> of variables
Examples
list_vars(xpose::xpdb_ex_pk)
list_vars(xpdb_x)
Log-likelihood, AIC and BIC for xpose_data objects
Description
NONMEM (and nlmixr2) objective function values (OFV) are -2*log-likelihood,
so the log-likelihood of a model is derived as -ofv/2. The number of estimated
parameters (thetas, and unfixed omegas/sigmas) is used as the degrees of freedom.
Because <stats::AIC> and <stats::BIC> dispatch through <stats::logLik>
by default, only logLik.xpose_data needs to be defined here for AIC()/BIC()
to work as expected on xpose_data/xp_xtras objects; no AIC/BIC methods
are defined for a single model.
Not calculable for a model-averaged ("franken") xpose_data object (eg, the
output of <modavg_xpdb>), since such an object does not correspond to a
single fitted model; an error is thrown instead.
Usage
## S3 method for class 'xpose_data'
logLik(object, .problem = NULL, .subprob = NULL, .method = NULL, ...)
Arguments
object |
< |
.problem |
< |
.subprob |
< |
.method |
< |
... |
Not used. |
Value
<logLik> object, as documented in <stats::logLik>, with "df"
(number of estimated parameters) and "nobs" (number of observations) attributes set.
Examples
logLik(xpdb_x)
AIC(xpdb_x)
BIC(xpdb_x)
Log-likelihood, AIC and BIC across an xpose_set
Description
If no base model is provided, and if lineage is unclear, the first model in
the xpose_set is used as the base model, exactly as in <diff.xpose_set>.
Unlike diff(), values are not differenced, so a straightforward
model-to-model comparison is possible.
As with the xpose_data methods, a component model that is itself a
model-averaged ("franken") object will cause an error.
Usage
## S3 method for class 'xpose_set'
logLik(object, ...)
## S3 method for class 'xpose_set'
AIC(object, ..., k = 2)
## S3 method for class 'xpose_set'
BIC(object, ...)
Arguments
object |
< |
... |
< |
k |
< |
Value
<numeric> vector, or list thereof, following <xset_lineage>.
Create a model-averaged xpose data object
Description
This function is a helper for plotting functions where models in
an xpose_set can be averaged together. The implementation attempts
to match and extend from the cited prior work.
Usage
modavg_xpdb(
xpdb_s,
...,
.lineage = FALSE,
avg_cols = NULL,
avg_by_type = NULL,
algorithm = c("maa", "msa"),
weight_type = c("individual", "population"),
auto_backfill = FALSE,
weight_basis = c("ofv", "aic", "res"),
res_col = "RES",
quiet
)
Arguments
xpdb_s |
< |
... |
< |
.lineage |
< |
avg_cols |
< |
avg_by_type |
< |
algorithm |
< |
weight_type |
< |
auto_backfill |
< |
weight_basis |
< |
res_col |
< |
quiet |
< |
Value
Weight-averaged <xpose_data> object.
References
Uster, D.W., Stocker, S.L., Carland, J.E., Brett, J., Marriott, D.J.E., Day, R.O. and Wicha, S.G. (2021), A Model Averaging/Selection Approach Improves the Predictive Performance of Model-Informed Precision Dosing: Vancomycin as a Case Study. Clin. Pharmacol. Ther., 109: 175-183. doi:10.1002/cpt.2065
Examples
pheno_set %>%
modavg_xpdb(
avg_cols = IPRED,
auto_backfill = TRUE,
algorithm = "maa",
weight_basis = "aic"
)
Add, remove or rename variables in an xpdb
Description
mutate_x() adds new variables and preserves existing ones.
select() keeps only the listed variables; rename() keeps all variables.
Note: this function uses xpose.xtras::edit_xpose_data, but is otherwise
the same as <xpose::mutate>.
Usage
mutate_x(.data, ..., .problem, .source, .where)
rename_x(.data, ..., .problem, .source, .where)
Arguments
.data |
An xpose database object. |
... |
Name-value pairs of expressions. Use |
.problem |
The problem from which the data will be modified |
.source |
The source of the data in the xpdb. Can either be 'data' or an output file extension e.g. 'phi'. |
.where |
A vector of element names to be edited in special (e.g.
|
Value
An updated xpose data object
Mutation method for xpose_set
Description
Mutation method for xpose_set
Usage
## S3 method for class 'xpose_set'
mutate(.data, ..., .force = FALSE, .retest = !.force, .rowwise = FALSE)
Arguments
.data |
< |
... |
< |
.force |
< |
.retest |
< |
.rowwise |
< |
Value
A set with updated top-level data (unless focused)
Examples
xpdb_set %>%
# Adds foo = bar for all objects in the set
mutate(foo = "bar") %>%
# Reshape to visualize
reshape_set()
Mutate the file table for an xpose data object
Description
Mutate the file table for an xpose data object
Usage
mutate_files(xpdb, ...)
Arguments
xpdb |
< |
... |
Forwarded to mutate() |
Transform parameter values in place
Description
Apply transformations to fitted parameter values.
As fitted, sometimes parameter values are not as easy to communicate, but
to transform them outside of the xpose ecosystem limits some available
features. To have the best experience, this function can update the
parameter values that are used by xpose get_prm functions. At this
time these transformations are not applied to param vars (list_vars), but that can
already be done with the mutate method.
This only works for theta parameters.
All valid mutations are applied sequentially, so a double call to the2~the2^3
will result in effectively the2~the2^9, for example.
RSE values are calculated at runtime within get_prm, so they are not updated (or
updatable) with this function.
Usage
mutate_prm(
xpdb,
...,
.autose = TRUE,
.problem = NULL,
.subprob = NULL,
.method = NULL,
.sesim = 1e+05,
quiet
)
Arguments
xpdb |
< |
... |
... < |
.autose |
< |
.problem |
< |
.subprob |
< |
.method |
< |
.sesim |
< |
quiet |
Silence extra output. |
Details
Important points about covariance and correlation (for NONMEM only)
Covariance and correlation parameters are adjusted when standard error (SE)
values are changed directly or with .autose. When a transformation is applied
as a function for the fixed effect parameter (eg, ~plogis), the resulting SE may have
an unexpected scale; this is because it is now reporting the standard deviation
of a transformed and potentially non-normal distribution. If the parameter were fit
in the transformed scale (constrained to any appropriate bounds), it would likely have a
different SE given that most covariance estimation methods (excluding non-parametric and
resampling-based) will treat the constrained parameter as continuous and unconstrained.
The updates to variance-covariance values (and the correlation values, though that is mostly
invariant) are applied to the entire matrices. When piped directly into
get_prm, only the SE estimate is shown, but <get_file> can be used
to see the complete updated variance-covariance values. This could be useful if those
matrices are being used to define priors for a Bayesian model fitting, as the re-scaling
of off-diagonal elements is handled automatically.
For all software: A function to transform parameters will result in a more accurate autose
result. If a call (the1~exp(the)) or a value (the1~2) are used, the standard error
will be simply scaled.
Value
An updated xp_xtras object with mutated parameters
Examples
vismo_pomod %>%
# Function
mutate_prm(THETA11~exp) %>%
# Value (se will not be scaled); plogis = inverse logit
mutate_prm(THETA12~plogis(THETA12)) %>%
get_prm()
Convenience function for ingesting an nlmixr2 model to xpose and xpose.xtras
Description
A wrapper that executes the pipeline:
obj |> xpose.nlmixr2::xpose_data_nlmixr2() |> attach_nlmixr2() |> as_xp_xtras() |> backfill_nlmixr2_props() `if`(.skip_assoc, ., nlmixr2_prm_associations(.))
Usage
nlmixr2_as_xtra(obj, ..., .skip_assoc = FALSE)
Arguments
obj |
nlmixr2 fit object |
... |
Passed to xpose_data_nlmixr2 |
.skip_assoc |
< |
Value
An <xp_xtra> object with fit attached
See Also
Based on associations baked into nlmixr2, automatically add to xpose data
Description
This function attempts to discern the associations between omegas and thetas
using information about mu referencing within the nlmixr2 fit object.
Usage
nlmixr2_prm_associations(xpdb, dry_run = FALSE, quiet)
Arguments
xpdb |
< |
dry_run |
< |
quiet |
< |
Details
Back-transformations are not as relevant here as they may seem. Manual
back-transformation with backTransform() only affects the display of the
back-transformed theta estimate (and CI), but does not impact the
relationship between EBEs and individual parameter estimates.
Value
Object with filled par
See Also
Examples
## Not run:
nlmixr2_warfarin <- nlmixr_example("nlmixr2_warfarin")
nlmixr2_warfarin %>%
# This will add all log-normal and the logitnormal params
nlmixr2_prm_associations() %>%
# Make sure theta is in normal scale
# rxode::expit could be plogis in this case
mutate_prm(temax ~ rxode2::expit) %>%
# Review results
get_prm()
## End(Not run)
Generate example xp_xtras objects from nlmixr2 fits
Description
Runs an nlmixr2 fit on demand and returns the result as a ready-to-use
xp_xtras object. nlmixr2_example is an alias.
Usage
nlmixr_example(name)
nlmixr2_example(name)
Arguments
name |
< |
Details
Available examples:
"xpdb_nlmixr2"One-compartment FOCEI fit to the theophylline dataset. The basic introductory example from the nlmixr2 documentation. See Theoph.
"xpdb_nlmixr2_saem"The same one-compartment theophylline model fit with SAEM instead of FOCEI.
"nlmixr2_warfarin"Multiple-endpoint warfarin PK/PD model with a four-compartment PK and turnover PD. Provides categorical covariate data useful for eta diagnostic examples.
"nlmixr2_m3"Theophylline one-compartment model with censoring applied to provoke M3 likelihood handling. Includes a
BLQLIKEoutput variable for use as a categorical DV example withcatdv_vs_dvprobs()."xpdb_nlmixr2_nocov"The same one-compartment theophylline FOCEI fit as
"xpdb_nlmixr2", but with the covariance step skipped (covMethod = ""). Useful for exercising code paths that depend on parameter uncertainty, such asget_cov_matrix(), when it is not available.
Value
An xp_xtras object with the nlmixr2 fit attached.
Source
"xpdb_nlmixr2" and "xpdb_nlmixr2_saem":
https://nlmixr2.org/articles/running_nlmixr.html
"nlmixr2_warfarin":
https://nlmixr2.org/articles/multiple-endpoints.html
"nlmixr2_m3":
https://github.com/nlmixr2/nlmixr2/issues/275#issuecomment-2445469327
References
Fidler M (2025). nlmixr2: Nonlinear Mixed Effects Models in Population PK/PD. doi:10.32614/CRAN.package.nlmixr2, R package version 3.0.2, https://CRAN.R-project.org/package=nlmixr2.
Fidler M, Wilkins J, Hooijmaijers R, Post T, Schoemaker R, Trame M, Xiong Y, Wang W (2019). "Nonlinear Mixed-Effects Model Development and Simulation Using nlmixr and Related R Open-Source Packages." CPT: Pharmacometrics & Systems Pharmacology, 8(9), 621-633. doi:10.1002/psp4.12445.
Schoemaker R, Fidler M, Laveille C, Wilkins J, Hooijmaijers R, Post T, Trame M, Xiong Y, Wang W (2019). "Performance of the SAEM and FOCEI Algorithms in the Open-Source, Nonlinear Mixed Effect Modeling Tool nlmixr." CPT: Pharmacometrics & Systems Pharmacology, 8(12), 923-930. doi:10.1002/psp4.12471.
Beal, S.L. Ways to Fit a PK Model with Some Data Below the Quantification Limit. J Pharmacokinet Pharmacodyn 28, 481-504 (2001). doi:10.1023/A:1012299115260
See Also
nlmixr2_as_xtra(), catdv_vs_dvprobs()
Examples
## Not run:
xpdb_nlmixr2 <- nlmixr_example("xpdb_nlmixr2")
nlmixr2_m3 <- nlmixr_example("nlmixr2_m3")
nlmixr2_m3 %>%
set_var_types(catdv = CENS, dvprobs = BLQLIKE) %>%
set_dv_probs(1, 1 ~ BLQLIKE, .dv_var = CENS) %>%
set_var_levels(1, CENS = lvl_bin()) %>%
catdv_vs_dvprobs(xlab = "basic", quiet = TRUE)
## End(Not run)
Select parameter row number
Description
The selection rules are described in <add_prm_association>.
Usage
param_selector(sel, prm_tbl)
Arguments
sel |
< |
prm_tbl |
< |
Value
<integer> of selected row number. Can be used to
get value and other elements of information from prm_tbl.
Patch condition number extraction
Description
Bugfix for xpose:::sum_condn, the internal function xpose uses to
populate the 'condn' (condition number) entry of xpdb$summary.
For NONMEM runs with more than one estimation method (e.g. SAEM followed
by importance sampling), the .lst file contains more than one
EIGENVALUES OF COR MATRIX OF ESTIMATE block. xpose always uses the
first block found, which is not necessarily from the final estimation
method, so the reported condition number can be wrong. This patch instead
uses the last block, matching the value reported by NONMEM-adjacent
tools such as PsN's sumo.
Usage
patch_condn(xpdb)
Arguments
xpdb |
An |
Value
The xpdb object, with a corrected 'condn' entry in
xpdb$summary (unchanged if xpdb is not from nonmem, or if
no eigenvalues could be found).
Examples
xpdb_ex_pk <- patch_condn(xpose::xpdb_ex_pk)
Write current process presets out to a .Rprofile
Description
Syncs the in-session add_process_preset() registry out to a
.Rprofile file, so it's available again in future sessions. This is
what persist = TRUE on add_process_preset()/remove_process_preset()/
amend_process_preset() calls internally; call it directly to persist
several in-session changes (each made with persist = FALSE) in one
write/confirmation instead of one per change. See the CRAN-policy notes
in add_process_preset() – in particular, this always errors instead
of writing anything when rlang::is_interactive() is FALSE.
Usage
persist_process_presets(ask = TRUE, profile = "project")
Arguments
ask |
< |
profile |
< |
Value
TRUE if the file was written, FALSE if declined (invisibly)
Examples
## Not run:
add_process_preset(~ .x %>% as_xpdb_x(), name = "convert", persist = FALSE)
persist_process_presets()
## End(Not run)
An xp_xtras example of a base model
Description
Base model for phenobarbital in neonates.
Usage
pheno_base
Format
xp_xtras
An xp_xtras object.
Details
This is run6 in <pheno_set>
Source
doi:10.1159/000457062 and nlmixr2data::pheno_sd
An xp_xtras example of a final model
Description
Final model for phenobarbital in neonates.
Usage
pheno_final
Format
xp_xtras
An xp_xtras object.
Details
This is re-parameterized from the covariate-building work, which in this case did not identify a relationship with Apgar score.
This is run16 in <pheno_set>
Source
doi:10.1159/000457062 and nlmixr2data::pheno_sd
An xp_xtras example of a final model
Description
Final model for phenobarbital in neonates.
Usage
pheno_saem
Format
xp_xtras
An xp_xtras object.
Details
This is the same as pheno_final but fitted with SAEM/IMP.
Not a part of <pheno_set>
Source
doi:10.1159/000457062 and nlmixr2data::pheno_sd
A more complex example of xpose_set object
Description
Model-building set for the phenobarbital in neonates PK data used across multiple packages.
Usage
pheno_set
Format
xpose_set
An xpose_set object of length 14 with a branched lineage.
Details
This is not a demonstration of high-quality model-building, it is just a typical and simple example.
Source
doi:10.1159/000457062 and nlmixr2data::pheno_sd
An xp_xtras example of an M3 model
Description
A representative PK/PD model with M3 fitting applied.
Usage
pkpd_m3
Format
xp_xtras
An xp_xtras object.
Source
References
Beal, S.L. Ways to Fit a PK Model with Some Data Below the Quantification Limit. J Pharmacokinet Pharmacodyn 28, 481-504 (2001). doi:10.1023/A:1012299115260
Prybylski JP. Indirect modeling of derived outcomes: Are minor prediction discrepancies a cause for concern? CPT Pharmacometrics Syst Pharmacol. 2024; 00: 1-9. doi:10.1002/psp4.13219
Examples
# To establish as a complete categorical DV example:
pkpd_m3 <- pkpd_m3 %>%
# Need to ensure var types are set
set_var_types(catdv=BLQ,dvprobs=LIKE) %>%
# Set probs
set_dv_probs(1, 1~LIKE, .dv_var = BLQ) %>%
# Optional, but useful to set levels
set_var_levels(1, BLQ = lvl_bin())
An xp_xtras example of an M3 model (dataset)
Description
The dataset used to fit the pkpd_m3 model.
Usage
pkpd_m3_df
Format
xp_xtras
An xp_xtras object.
Source
References
Prybylski JP. Indirect modeling of derived outcomes: Are minor prediction discrepancies a cause for concern? CPT Pharmacometrics Syst Pharmacol. 2024; 00: 1-9. doi:10.1002/psp4.13219
Generate a batch of diagnostic plots from an xpdb
Description
Runs a list of plot-generating calls against x in one go, returning a
flat, named list of the results. Each element of plots (or the
resolved default, see Details) is either:
a bare function taking a single
xpdbargument, ora one-sided formula in the
~ fn(.x)idiom used elsewhere in this package (seefocus_function()), letting extra arguments be baked straight into the call – e.g.~ xpose::res_vs_idv(.x, res = "CWRES").
Both forms are converted to callables with purrr::as_mapper(). Because
entries are just calls, the same underlying plot function can appear
more than once with different options (e.g. res_vs_idv for both CWRES
and IWRES) – see the examples.
If a single entry itself returns a list of plots (as e.g. eta_grid()
can, given more than one eta), that list is flattened into the overall
output rather than kept as a nested list – so the return value is
always a flat list of ggplot/xpose_plot objects.
Usage
## S3 method for class 'xpose_data'
plot(x, y, plots, ..., force = FALSE, quiet)
Arguments
x |
< |
y |
unused; present only for consistency with the
|
plots |
A list of plot specs (see Description); defaults to the resolved value described in Details |
... |
unused |
force |
< |
quiet |
< |
Details
plots is resolved, in increasing precedence, from: this package's
built-in default (dv_vs_ipred, dv_vs_pred, res_vs_idv,
res_vs_pred, eta_distrib, eta_grid, eta_vs_cov_grid,
ind_plots_sample), the xpose.xtras.default_plots session option, an
xpdb-level default set via set_default_plots(), and finally the
plots argument itself, if supplied.
A loading spinner is shown (interactive sessions only, unless
quiet = TRUE) while plots are generated. If a plot fails to generate,
the default (force = FALSE) is to immediately raise an error (showing
the original error as its parent) without returning any plots at all.
With force = TRUE, a failure is instead emitted as a warning and that
entry is skipped, so the rest of plots still gets a chance to run.
Value
A flat, named list of ggplot/xpose_plot objects
Examples
# the package's built-in default battery of diagnostic plots
default_plots <- plot(xpdb_x, quiet = TRUE)
names(default_plots)
# a custom spec: bare functions, formulas, and the same function twice
custom_plots <- plot(
xpdb_x,
plots = list(
xpose::dv_vs_ipred,
~ xpose::res_vs_idv(.x, res = "CWRES"),
~ xpose::res_vs_idv(.x, res = "IWRES")
),
quiet = TRUE
)
names(custom_plots)
Draw an xpose_plot object
Description
This function explicitly draw an xpose_plot and interprets keywords contained in labels.
Usage
## S3 method for class 'xpose_plot'
print(x, page, ...)
Arguments
x |
An |
page |
The page number to be drawn. Can be specified as vector or range of integer values. |
... |
Options to be passed on to the ggplot2 print method. |
Examples
my_plot <- xpose::dv_vs_ipred(xpose::xpdb_ex_pk) +
ggplot2::labs(title = 'A label with keywords: @nind individuals & @nobs observations')
# Using the print function
print(my_plot)
# Or simply by writing the plot object name
my_plot
Continuous/categorical covariate effect tables
Description
Computes, for each covariate association declared with
add_cov_association(), the covariate's effect on the associated
parameter (as a ratio to the parameter's typical value, 1 at the
reference covariate value/level) at a handful of representative
evaluation points, with an uncertainty interval propagated from the
effect-size theta's standard error. This is what xplot_forest()
plots; calling these directly is mostly useful for inspecting the
numbers before/without plotting.
prm_contcov() handles continuous covariates (linear, power,
exponential, hockey, or custom associations), evaluated at the
low/reference/high points. prm_catcov() handles categorical
covariates (catshift or custom associations), evaluated at every
observed level. prm_cov() combines both.
Usage
prm_contcov(
xpdb,
...,
.problem = NULL,
.subprob = NULL,
.method = NULL,
ci_method = c("simulation", "delta"),
probs = c(0.05, 0.95),
level = 0.95,
nsim = 1000,
keep_draws = FALSE,
quiet
)
prm_catcov(
xpdb,
...,
.problem = NULL,
.subprob = NULL,
.method = NULL,
ci_method = c("simulation", "delta"),
level = 0.95,
nsim = 1000,
keep_draws = FALSE,
quiet
)
prm_cov(
xpdb,
...,
.problem = NULL,
.subprob = NULL,
.method = NULL,
ci_method = c("simulation", "delta"),
probs = c(0.05, 0.95),
level = 0.95,
nsim = 1000,
keep_draws = FALSE,
quiet
)
Arguments
xpdb |
< |
... |
< |
.problem |
< |
.subprob |
< |
.method |
< |
ci_method |
< |
probs |
< |
level |
< |
nsim |
< |
keep_draws |
< |
quiet |
Silence extra output. |
Value
A prm_cov_tbl tibble with one row per (parameter, covariate,
evaluation point):
param, covariate, covtype, level ("low"/"ref"/"high" for
continuous, the raw category value for categorical), value (the
covariate value/level backing that row), is_ref (TRUE for the
reference row/level – always effect/ci_low/ci_high == 1, by
construction), effect, ci_low, ci_high, ci_method.
See Also
add_cov_association(), xplot_forest()
Examples
xpdb_x %>%
add_cov_association(TVCL ~ power(CLCR, THETA7, ref = 64)) %>%
prm_contcov()
xpdb_x %>%
add_cov_association(TVCL ~ catshift(SEX, THETA4, ref = 1)) %>%
prm_catcov()
xpdb_x %>%
add_cov_association(
TVCL ~ power(CLCR, THETA7, ref = 64),
TVCL ~ catshift(SEX, THETA4, ref = 1)
) %>%
prm_cov()
# Restrict to one association, and use the analytic delta-method CI
xpdb_x %>%
add_cov_association(
TVCL ~ power(CLCR, THETA7, ref = 64),
TVCL ~ catshift(SEX, THETA4, ref = 1)
) %>%
prm_cov(TVCL ~ CLCR, ci_method = "delta")
Specific waterfall plots
Description
Differences are second listed model minus first listed. Eg, in
eta_waterfall(run1,run2), the when etas in run2 are greater than
those in run1, the difference will be positive.
Usage
prm_waterfall(
xpdb_s,
...,
.inorder = FALSE,
type = "bh",
max_nind = 0.7,
scale_diff = TRUE,
show_n = TRUE,
title = "Parameter changes between models | @run",
subtitle = "Based on @nobs observations in @nind individuals",
caption = "@dir",
tag = NULL,
facets = NULL,
facet_scales = "free_x",
.problem,
.subprob,
.method,
quiet
)
eta_waterfall(
xpdb_s,
...,
.inorder = FALSE,
type = "bh",
max_nind = 0.7,
scale_diff = TRUE,
show_n = TRUE,
title = "Eta changes between models | @run",
subtitle = "Based on @nobs observations in @nind individuals",
caption = "@dir",
tag = NULL,
facets = NULL,
facet_scales = "free_x",
.problem,
.subprob,
.method,
quiet
)
iofv_waterfall(
xpdb_s,
...,
.inorder = FALSE,
type = "bh",
max_nind = 0.7,
scale_diff = FALSE,
show_n = TRUE,
title = "iOfv changes between models | @run",
subtitle = "Based on @nobs observations in @nind individuals",
caption = "@dir",
tag = NULL,
facets = NULL,
facet_scales = "free_x",
.problem,
.subprob,
.method,
quiet
)
Arguments
xpdb_s |
< |
... |
See < |
.inorder |
See < |
type |
See Details. |
max_nind |
If less than 1, the percentile of absolute change values above which to plot. If above 1, the absolute number of subjects is included. To show all, use an extreme positive number like 9999. |
scale_diff |
< |
show_n |
< |
title |
Plot title |
subtitle |
Plot subtitle |
caption |
Plot caption |
tag |
Plot tag |
facets |
< |
facet_scales |
< |
.problem |
The problem to be used, by default returns the last one. |
.subprob |
The subproblem to be used, by default returns the last one. |
.method |
The estimation method to be used, by default returns the last one. |
quiet |
Silence extra debugging output |
Details
For type-based customization of plots:
-
bbar plot (fromgeom_bar) -
hhline at 0 (fromgeom_hline) -
ttext of change value (fromgeom_text)
Value
<xpose_plot> object
Examples
# Parameter value changes
pheno_set %>%
# Ensure param is set
focus_qapply(set_var_types, param=c(CL,V)) %>%
prm_waterfall(run5,run6)
# EBE value changes
pheno_set %>%
eta_waterfall(run5,run6)
# iOFV changes
pheno_set %>%
focus_qapply(backfill_iofv) %>%
# Note the default scaling is flipped here
iofv_waterfall(run5,run6)
Convert levels list into tibble
Description
Consumes formula list and converts into corresponding tibble.
Usage
proc_levels(lvl_list)
Arguments
lvl_list |
< |
Value
<tibble> of levels
Pulling method for xpose_set
Description
Pulling method for xpose_set
Usage
## S3 method for class 'xpose_set'
pull(.data, ...)
Arguments
.data |
< |
... |
< |
Value
The top-level information for a set requested.
Examples
xpdb_set %>%
pull(xpdb)
Objects exported from other packages
Description
These objects are imported from other packages. Follow the links below to see their documentation.
Renaming method for xpose_set
Description
Renaming method for xpose_set
Usage
## S3 method for class 'xpose_set'
rename(.data, ...)
Arguments
.data |
< |
... |
< |
Value
Re-labeled set
Examples
xpdb_set %>%
rename(Mod = mod1)
Reportable digits for model fit
Description
An opinionated function where for optimization routines that report number of significant digits (eg, FO-based), only those number of digits are considered reportable.
Usage
reportable_digits(xpdb, .default = 3, .problem, .subprob, .method)
Arguments
xpdb |
< |
.default |
< |
.problem |
< |
.subprob |
< |
.method |
< |
Value
Number of reportable digits
Examples
reportable_digits(xpdb_x)
Convert xpose_set to a nested list.
Description
This amounts to a convenience function for tidy manipulations.
Usage
reshape_set(x)
unreshape_set(y)
Arguments
x |
< |
y |
< |
Value
<tibble> Nested list, or <xpose_set>
Examples
rset <- reshape_set(xpdb_set)
# Properties (exposed and top-level) can be seen. xpdb objects are nested in the xpdb column.
rset %>% dplyr::select(-xpdb) %>% dplyr::glimpse()
unreshape_set(rset)
# The reversibility of reshaping can be confirmed:
identical(xpdb_set,reshape_set(xpdb_set) %>% unreshape_set())
ROC curve across models
Description
Faceted display of ROC curves across models in a set.
Usage
roc_by_mod(
xpdb_s,
...,
.lineage = FALSE,
mapping = NULL,
cutpoint = 1,
type = "ca",
title = "ROC curves across models | @dvcol~@probcol",
subtitle = "Based on @nind individuals, Ofvs: @ofv",
caption = "@dir",
tag = NULL,
axis.text = "@run",
facets,
.problem,
quiet,
roc_args = NULL
)
Arguments
xpdb_s |
< |
... |
Any additional aesthetics. |
.lineage |
< |
mapping |
|
cutpoint |
< |
type |
See Details. |
title |
Plot title |
subtitle |
Plot subtitle |
caption |
Plot caption |
tag |
Plot tag |
axis.text |
What to label the model. This is parsed on a per-model basis. |
facets |
Additional facets |
.problem |
Problem number |
quiet |
Silence extra debugging output |
roc_args |
Additional arguments to pass to |
Details
For type-based customization of plots:
-
cROC curve (usinggeom_path) -
kKey points on ROC curve (where on curve the threshold isthres_fixed) (usinggeom_point) -
pROC space points (usinggeom_point) -
tROC space text (usinggeom_text) -
aAUC in bottom right (usinggeom_label)
Examples
pkpd_m3 <- pkpd_m3 %>%
# Need to ensure var types are set
set_var_types(catdv=BLQ,dvprobs=LIKE) %>%
# Set probs
set_dv_probs(1, 1~LIKE, .dv_var = BLQ) %>%
# Optional, but useful to set levels
set_var_levels(1, BLQ = lvl_bin())
m3_set <- xpose_set(
run1=set_prop(pkpd_m3,run="run1"),
run2=set_prop(pkpd_m3,run="run2"),
run3=set_prop(pkpd_m3,run="run3")
)
roc_by_mod(m3_set, type = "ck", quiet = TRUE)
ROC Plot for categorical DVs
Description
ROC Plot for categorical DVs
Usage
roc_plot(
xpdb,
mapping = NULL,
cutpoint = 1,
group = "ID",
type = "ca",
title = "ROC curve @dvcol~@probcol | @run",
subtitle = "Ofv: @ofv, Eps shrink: @epsshk",
caption = "@dir",
tag = NULL,
guide = TRUE,
facets,
.problem,
quiet,
...
)
Arguments
xpdb |
< |
mapping |
|
cutpoint |
< |
group |
Variable by which to group points or text |
type |
See Details. |
title |
Plot title |
subtitle |
Plot subtitle |
caption |
Plot caption |
tag |
Plot tag |
guide |
Include unity line? |
facets |
Additional facets |
.problem |
Problem number |
quiet |
Silence extra debugging output |
... |
Any additional aesthetics. |
Details
For type-based customization of plots:
-
cROC curve (usinggeom_path) -
kKey points on ROC curve (where on curve the threshold isthres_fixed) (usinggeom_point) -
pROC space points (usinggeom_point) -
tROC space text (usinggeom_text) -
aAUC in bottom right (usinggeom_label)
Value
A desired plot
See Also
Examples
# Note these examples are similar to catdv_vs_dvprobs
## Not run:
# Test M3 model
pkpd_m3 %>%
# Need to ensure var types are set
set_var_types(catdv=BLQ,dvprobs=LIKE) %>%
# Set probs
set_dv_probs(1, 1~LIKE, .dv_var = BLQ) %>%
# Optional, but useful to set levels
set_var_levels(1, BLQ = lvl_bin()) %>%
# Generate typical ROC curve
roc_plot()
# Test categorical model
vismo_xpdb <- vismo_pomod %>%
set_var_types(.problem=1, catdv=DV, dvprobs=matches("^P\\d+$")) %>%
set_dv_probs(.problem=1, 0~P0,1~P1,ge(2)~P23)
# Various cutpoints (note axes labels and texts)
vismo_xpdb %>%
roc_plot(type = "p") # space plot
vismo_xpdb %>%
roc_plot(cutpoint=2, type = "cak") # with area and key point
vismo_xpdb %>%
roc_plot(cutpoint=3, type = "cak")
# alternative model example
vismo_xpdb2 <- vismo_dtmm %>%
set_var_types(.problem=1, catdv=DV, dvprobs=matches("^P\\d+$")) %>%
set_dv_probs(.problem=1, 0~P0,1~P1,ge(2)~P23)
vismo_xpdb2 %>%
roc_plot(cutpoint=2, type = "cak")
## End(Not run)
Selection method for xpose_set
Description
Selection method for xpose_set
Usage
## S3 method for class 'xpose_set'
select(.data, ...)
Arguments
.data |
< |
... |
< |
Value
Subset of xpose set
Examples
xpdb_set %>%
select(starts_with("fix"))
xpdb_set %>%
select(mod1, fix1)
Convenience wrapper for tidyselect
Description
This is intended for use as an internal function to select a subset of xpdb objects from an xpose_set.
It is a lower level version of <select.xpose_set>
Usage
select_subset(xpdb_s, ...)
Arguments
xpdb_s |
< |
... |
< |
Value
<numeric> vector of indices for selected xpdb objects
Examples
select_subset(mod2, xpdb_s=xpdb_set)
select_subset(dplyr::starts_with("fix"), xpdb_s=xpdb_set)
Base model for xpose_set
Description
Base model for xpose_set
Usage
set_base_model(xpdb_s, ...)
get_base_model(xpdb_s)
unset_base_model(xpdb_s)
Arguments
xpdb_s |
< |
... |
<< |
Value
<xpose_set> object with a base model
Examples
w_base <- xpdb_set %>%
set_base_model(mod2)
w_base # base model listed in output
get_base_model(w_base) # base model name
unset_base_model(w_base) # base model no longer in output
Set default plot label overrides on an xp_xtras object
Description
Stores title/subtitle/caption/tag templates on xpdb that
apply_default_labs() will use to fill in (or overwrite) labels on any
plot built from this xpdb, when xpdb is passed to it. Values may
contain the same @keyword placeholders understood by
xpose::parse_title() (e.g. "@nind", "@nobs", "@run"), since
they are resolved the same way.
Usage
set_default_labs(xpdb, ...)
Arguments
xpdb |
< |
... |
< |
Value
xp_xtras object
See Also
set_xtras_options() for the session-option equivalent
(xpose.xtras.default_labs), and get_xtras_option() to check which
one is currently dominant.
Examples
xpdb_x <- set_default_labs(xpdb_x, caption = "@nobs observations in @nind individuals")
p <- xpose::dv_vs_ipred(xpdb_x)
apply_default_labs(p, xpdb = xpdb_x)
Set a default plot spec on an xp_xtras object
Description
Stores a plot spec on xpdb that plot.xpose_data() uses instead of
the package's built-in default whenever plots isn't supplied directly
to that call. Unlike set_default_labs()/set_default_watermark(),
this replaces the xpdb-level default wholesale rather than merging
with it: entries in a plot spec aren't addressable by a stable key (the
same plot function can legitimately appear more than once), so there is
no sensible key-by-key merge to perform.
Usage
set_default_plots(xpdb, plots)
Arguments
xpdb |
< |
plots |
A list of plot specs – see plot.xpose_data() for the accepted forms |
Value
xp_xtras object
See Also
set_xtras_options() for the session-option equivalent
(xpose.xtras.default_plots), and get_xtras_option() to check which
one is currently dominant.
Examples
xpdb2 <- set_default_plots(xpdb_x, list(~ xpose::dv_vs_ipred(.x), ~ xpose::eta_distrib(.x)))
names(plot(xpdb2, quiet = TRUE))
Set default watermark options on an xp_xtras object
Description
Stores default add_watermark() arguments on xpdb that
add_watermark() will use for any of label/colour/alpha/size/
angle/fontface not otherwise supplied, when xpdb is passed to it.
Usage
set_default_watermark(xpdb, ...)
Arguments
xpdb |
< |
... |
< |
Value
xp_xtras object
See Also
set_xtras_options() for the session-option equivalent
(xpose.xtras.default_watermark), and get_xtras_option() to check
which one is currently dominant.
Examples
xpdb_x <- set_default_watermark(xpdb_x, label = "PRELIMINARY", colour = "red")
p <- xpose::dv_vs_ipred(xpdb_x)
add_watermark(p, xpdb = xpdb_x)
Set probability columns for categorical endpoints
Description
For categorical DVs or similar endpoints (such as censoring
flag columns, like BLQ), this function allows probability
columns to be defined for each level.
Usage
set_dv_probs(
xpdb,
.problem = NULL,
...,
.dv_var = NULL,
.handle_missing = c("quiet", "warn", "error")
)
Arguments
xpdb |
< |
.problem |
< |
... |
Formulas where LHS are levels or pseudo-functions (see Details), and RHS are columns with probabilities of those levels. |
.dv_var |
< |
.handle_missing |
< |
Details
The same probability cannot be assigned to multiple values. Pseudo-functions can be used, or
new columns can be created to overcome this limitation. The available pseudo-functions should
be written like ge(value) (for >=), gt(value) (for >), etc. These comparison names
are those used in Perl, Fortran and many other languages. The function eq() should not be used,
but it will be ignored either way; equivalence is implied with the base syntax.
Value
<xp_xtras> object with updated probabilities
Examples
pkpd_m3 %>%
# Not necessary, but correct to set var type before using this
set_var_types(.problem=1, catdv=BLQ, dvprobs=LIKE) %>%
# Set var type. Warnings can be helpful unless an inverse likelihood column is available
set_dv_probs(.problem=1, 1~LIKE, .dv_var = BLQ, .handle_missing = "warn") %>%
list_vars()
# Same as above with demo of inverse column
pkpd_m3 %>%
xpose::mutate(INVLIKE = 1-LIKE) %>%
set_var_types(.problem=1, catdv=BLQ, dvprobs=c(LIKE,INVLIKE)) %>%
# Note no warning
set_dv_probs(.problem=1, 1~LIKE, 0~INVLIKE, .dv_var = BLQ, .handle_missing = "warn")%>%
list_vars()
# With categorical model
vismo_pomod %>%
# Update var types
set_var_types(.problem=1, catdv=DV, dvprobs=matches("^P\\d+$")) %>%
# Warning (as noted), does not recognize 3 is covered implicitly. That's ok!
set_dv_probs(.problem=1, 0~P0,1~P1,ge(2)~P23, .handle_missing = "warn")%>%
list_vars()
# Same as above, but...
vismo_pomod %>%
set_var_types(.problem=1, catdv=DV, dvprobs=matches("^P\\d+$")) %>%
# Default is to not bother users with a warning
set_dv_probs(.problem=1, 0~P0,1~P1,ge(2)~P23)%>%
list_vars()
# .problem can be omitted for single-problem models
pkpd_m3 %>%
set_var_types(catdv=BLQ, dvprobs=LIKE) %>%
set_dv_probs(1~LIKE, .dv_var = BLQ) %>%
list_vars()
Set an xpose option
Description
Sets one or more entries in xpdb$options, merged in via
utils::modifyList() – which recurses into list-valued options, so
setting a single key of an existing named-list option (e.g. one label
of default_labs, see set_default_labs()) leaves its other keys
untouched rather than replacing the whole list. This is what
set_default_labs() and set_default_watermark() are built on, and
calling set_option() directly with default_labs/default_watermark
behaves the same way.
Usage
set_option(xpdb, ...)
Arguments
xpdb |
< |
... |
< |
Value
xp_xtras object
Examples
xpdb_x <- set_option(xpdb_x, quiet = TRUE)
Set a summary property
Description
Set a summary property
Usage
set_prop(xpdb, ..., .problem = NULL, .subprob = NULL)
Arguments
xpdb |
< |
... |
< |
.problem |
< |
.subprob |
< |
Details
Although one might be tempted to set custom properties using this function,
with the intention to maintain cross-functionality with xpose, users cannot
set a non-existent property with this function. When used internally, workarounds
to this semi-limitation are used.
Value
xp_xtras object
Examples
set_prop(xpose::xpdb_ex_pk, descr = "New model description") %>%
xpose::get_summary()
Set variable levels
Description
For variable types such as catcov, it can be convenient to define
levels. This function provides a straightforward means to do so,
consistent with tidy functions like <case_when>.
Several convenience functions are provided for common levels in <levelers>.
Usage
set_var_levels(
xpdb,
.problem = NULL,
...,
.missing = "Other",
.ordered = character(),
.handle_missing = c("quiet", "warn", "error")
)
Arguments
xpdb |
< |
.problem |
< |
... |
< |
.missing |
< |
.ordered |
< |
.handle_missing |
< |
Value
<xp_xtras> object with updated levels
Examples
set_var_levels(xpdb_x,
SEX = lvl_sex(),
MED1 = lvl_bin(),
MED2 = c(
0 ~ "n",
1 ~ "y"
)
)
Set variable types
Description
<set_var_types> wrapper that accepts tidyselect syntax.
Character vector-based selection still works.
set_var_types_x accepts xpose_data or xp_xtras objects.
set_var_types without _x is defined with S3 methods. To maintain xpose expectations,
the default method is <set_var_types>, but if an xp_xtras object
is used, the method uses set_var_types_x.
Usage
set_var_types(xpdb, .problem = NULL, ..., auto_factor = TRUE, quiet)
Arguments
xpdb |
An |
.problem |
The problem number to which the edits will be applied. |
... |
< |
auto_factor |
If |
quiet |
Logical, if |
Value
An xpose_data object
Examples
data("xpdb_ex_pk", package = "xpose")
# Change variable type
xpdb_2 <- set_var_types_x(
xpdb_ex_pk, .problem = 1,
idv = TAD,
catcov = starts_with("MED"),
contcov = c(CLCR,AGE)
)
Set variable types
Description
<set_var_types> wrapper that accepts tidyselect syntax.
Character vector-based selection still works.
set_var_types_x accepts xpose_data or xp_xtras objects.
set_var_types without _x is defined with S3 methods. To maintain xpose expectations,
the default method is <set_var_types>, but if an xp_xtras object
is used, the method uses set_var_types_x.
Usage
## Default S3 method:
set_var_types(xpdb, .problem = NULL, ..., auto_factor = TRUE, quiet)
Arguments
xpdb |
An |
.problem |
The problem number to which the edits will be applied. |
... |
< |
auto_factor |
If |
quiet |
Logical, if |
Value
An xpose_data object
Examples
data("xpdb_ex_pk", package = "xpose")
# Change variable type
xpdb_2 <- set_var_types_x(
xpdb_ex_pk, .problem = 1,
idv = TAD,
catcov = starts_with("MED"),
contcov = c(CLCR,AGE)
)
Set variable types
Description
<set_var_types> wrapper that accepts tidyselect syntax.
Character vector-based selection still works.
set_var_types_x accepts xpose_data or xp_xtras objects.
set_var_types without _x is defined with S3 methods. To maintain xpose expectations,
the default method is <set_var_types>, but if an xp_xtras object
is used, the method uses set_var_types_x.
Usage
## S3 method for class 'xp_xtras'
set_var_types(xpdb, .problem = NULL, ..., auto_factor = TRUE, quiet)
Arguments
xpdb |
An |
.problem |
The problem number to which the edits will be applied. |
... |
< |
auto_factor |
If |
quiet |
Logical, if |
Value
An xpose_data object
Examples
data("xpdb_ex_pk", package = "xpose")
# Change variable type
xpdb_2 <- set_var_types_x(
xpdb_ex_pk, .problem = 1,
idv = TAD,
catcov = starts_with("MED"),
contcov = c(CLCR,AGE)
)
Set variable types
Description
<set_var_types> wrapper that accepts tidyselect syntax.
Character vector-based selection still works.
set_var_types_x accepts xpose_data or xp_xtras objects.
set_var_types without _x is defined with S3 methods. To maintain xpose expectations,
the default method is <set_var_types>, but if an xp_xtras object
is used, the method uses set_var_types_x.
Usage
set_var_types_x(xpdb, .problem = NULL, ..., auto_factor = TRUE, quiet)
Arguments
xpdb |
An |
.problem |
The problem number to which the edits will be applied. |
... |
< |
auto_factor |
If |
quiet |
Logical, if |
Value
An xpose_data object
Examples
data("xpdb_ex_pk", package = "xpose")
# Change variable type
xpdb_2 <- set_var_types_x(
xpdb_ex_pk, .problem = 1,
idv = TAD,
catcov = starts_with("MED"),
contcov = c(CLCR,AGE)
)
Set xpose.xtras session options
Description
Convenience wrapper around base options() for the xpose.xtras.*
family of options recognized by this package. Prefixes are added
automatically and names are validated against the list below, so e.g.
set_xtras_options(save_dir = "figures") is equivalent to (but safer
against typos than) options(xpose.xtras.save_dir = "figures").
Current values can be read back with regular getOption() (e.g.
getOption("xpose.xtras.save_dir")), or with get_xtras_option() for
default_labs/default_watermark, which also considers any
xpdb-level default.
Usage
set_xtras_options(...)
Arguments
... |
< |
Details
Recognized options (all unset, i.e. NULL, by default, except
auto_apply which defaults to TRUE):
auto_applyWhether print.xpose_plot() and
ggsave_xp()automatically apply configureddefault_labs/default_watermark(labels always; a watermark only ifdefault_watermarkis actually set at some tier – there's no unprompted default watermark). Defaults toTRUE, but is a no-op untildefault_labs/default_watermarkare themselves configured, so leaving it at its default has no visible effect on its own; set it toFALSEto opt out of the auto-apply behavior everywhere at once (or passapply_labs/apply_watermarkto a specificggsave_xp()call to opt out just there).print.xpose_plot()only ever sees the session-wide option tier (not anxpdb-level one) for the same reason noted underdefault_labsbelow.default_labsNamed list of default
title/subtitle/caption/tagtemplates (may contain@keywordplaceholders, seexpose::parse_title()). Used byapply_default_labs()(and by extensionggsave_xp()) as the lowest-precedence source for any label a plot doesn't already have – xpdb-level defaults (seeset_default_labs()) and arguments passed directly toapply_default_labs()both take precedence over this option.default_watermarkNamed list of default
add_watermark()arguments (any oflabel/colour/alpha/size/angle/fontface). Used byadd_watermark()as the lowest-precedence source – xpdb-level defaults (seeset_default_watermark()) and arguments passed directly toadd_watermark()both take precedence over this option.default_plotsA list of plot specs (see plot.xpose_data()) used whenever
plotsisn't supplied directly to plot.xpose_data(). Unlikedefault_labs/default_watermark, this is resolved as a whole (not merged key by key) – xpdb-level defaults (seeset_default_plots()) take precedence over this option, and aplotsargument passed directly takes precedence over both.save_dir,save_width,save_heightDefaults for the
path/width/heightarguments ofggsave_xp(), used whenever those arguments aren't supplied explicitly.save_funDefault save function for
ggsave_xp()(itself defaulting toggplot2::ggsave()when this is unset), for swapping in a drop-in alternative such asreportifyr::ggsave_with_metadata()project-wide instead of passingsave_funto everyggsave_xp()call.gg_theme,xp_themeDefault
ggplot2theme /xposexp_theme(seexpose::update_themes()) applied to anxpose_dataobject the first time it's converted viaas_xpdb_x(), so a project-wide look can be set once per session instead of callingxpose::update_themes()on everyxpdbindividually. Has no effect onxpdbs that are alreadyxp_xtrasobjects.
Value
the previous values of the options that were set, invisibly
(see options())
See Also
get_xtras_option() to inspect which tier is currently
dominant for a two-tier option; apply_default_labs(),
add_watermark(), ggsave_xp(), and as_xpdb_x(), which consume
these options.
Examples
set_xtras_options(save_dir = "figures", default_watermark = list(label = "DRAFT"))
getOption("xpose.xtras.save_dir")
set_xtras_options(save_dir = NULL, default_watermark = NULL)
Change colors of shark plots
Description
This changes the point and text color
in the xp_theme of an xpose_data object.
Usage
shark_colors(
xpdb,
upcolor = xp_xtra_theme(base_on = xpdb$xp_theme)$sharkup_color,
dncolor = xp_xtra_theme(base_on = xpdb$xp_theme)$sharkdn_color
)
Arguments
xpdb |
< |
upcolor |
Color for increasing dOFV |
dncolor |
Color for decreasing dOFV |
Value
<xpose_data> object
See Also
Examples
# Where this would fit in a particular workflow
xpose_set(pheno_base, pheno_final) %>%
# forward functions affecting xpdb objects
focus_xpdb(everything()) %>%
# Add iOFVs
focus_function(backfill_iofv) %>%
# Change color of all xpdb xp_themes (though only the first one needs to change)
focus_function(
function(x) shark_colors(
x,
upcolor = "purple",
dncolor = "green"
)) %>%
# See new plot
shark_plot()
Individual contributions to dOFV
Description
This is intended to match the overall behavior of
dOFV.vs.id() in xpose4, within the framework
of the xpose_set object.
dofv_vs_id is an alias of the function shark_plot,
for recognition.
Usage
shark_plot(
xpdb_s,
...,
.inorder = FALSE,
type = "plt",
alpha = 0.05,
df = "guess",
text_cutoff = 0.8,
title = "Individual contributions to dOfv | @run",
subtitle = "Based on @nind individuals, Ofvs: @ofv",
caption = "@dir",
tag = NULL,
ylab = "dOfv",
xlab = "Number of individuals removed",
opt,
facets = NULL,
.problem,
.subprob,
.method,
quiet
)
dofv_vs_id(
xpdb_s,
...,
.inorder = FALSE,
type = "plt",
alpha = 0.05,
df = "guess",
text_cutoff = 0.8,
title = "Individual contributions to dOfv | @run",
subtitle = "Based on @nind individuals, Ofvs: @ofv",
caption = "@dir",
tag = NULL,
ylab = "dOfv",
xlab = "Number of individuals removed",
opt,
facets = NULL,
.problem,
.subprob,
.method,
quiet
)
Arguments
xpdb_s |
< |
... |
See < |
.inorder |
See < |
type |
See Details. |
alpha |
alpha for LRT |
df |
degrees of freedom for LRT. If |
text_cutoff |
If less than 1, the percentile of absolute individual dOFV values above which to show labels of IDs. If above 1, the absolute number of IDs to show. To show all, use an extreme positive number like 9999. |
title |
Plot title |
subtitle |
Plot subtitle |
caption |
Plot caption |
tag |
Plot tag |
ylab |
y-axis label |
xlab |
x-axis label |
opt |
User-specified data options. Only some of these will be used. |
facets |
< |
.problem |
The problem to be used, by default returns the last one. |
.subprob |
The subproblem to be used, by default returns the last one. |
.method |
The estimation method to be used, by default returns the last one. |
quiet |
Silence extra debugging output |
Details
For type-based customization of plots:
-
ppoints (using aesthetics forsharkupandsharkdn) -
llines for dOFV (both total dOFV and significance are plotted) -
ttext (using aesthetics forshkuptxtandshkdntxt)
In xpose4, users can control sig.drop, but this function uses
alpha and df to determine the critical delta by the likelihood
ratio test. It is acknowledged there are situations where this may
not be valid, but it is suggested that df or alpha be adjusted
to meet the desired sig.drop.
my_alpha <- 0.05 my_df <- 1.34 # fractional, perhaps to account for different IIVs my_sigdrop <- -stats::qchisq(1-my_alpha, my_df) my_sigdrop #> [1] -4.633671 # Then use alpha=my_alpha, df=my_df in `shark_plot` call.
Value
<xpose_plot> object
See Also
Examples
pheno_set %>%
# Make sure set has iofv var types defined
focus_xpdb(everything()) %>%
focus_function(backfill_iofv) %>%
# Pick two models or consistent with two_set_dots()
shark_plot(run6,run11)
pheno_set %>%
# As before
focus_xpdb(everything()) %>%
focus_function(backfill_iofv) %>%
# Add indicator (or use established covariate)
mutate(APGRtest = as.numeric(as.character(APGR))<5) %>%
# Pick two models or consistent with two_set_dots()
shark_plot(run6,run11, facets = "APGRtest")
Group/ungroup and summarize variables in an xpdb
Description
group_by_x() takes an existing table and converts it into a
grouped table where operations are performed "by group". ungroup() removes grouping.
summarize() reduces multiple values down to a single value.
Note: this function uses xpose.xtras::edit_xpose_data, but is otherwise
the same as <xpose::group_by>.
Usage
group_by_x(.data, ..., .problem, .source, .where)
ungroup_x(.data, ..., .problem, .source, .where)
Arguments
.data |
An xpose database object. |
... |
Name-value pairs of expressions. Use |
.problem |
The problem from which the data will be modified |
.source |
The source of the data in the xpdb. Can either be 'data' or an output file extension e.g. 'phi'. |
.where |
A vector of element names to be edited in special (e.g.
|
Value
Group data in an xpose data object
Test if xpose data object has a fit object
Description
Test if xpose data object has a fit object
Usage
test_nlmixr2_has_fit(xpdb)
Arguments
xpdb |
< |
Test if nlmixr2 fit is from an old rxode2 version
Description
Detects if an nlmixr2 fit object was created with rxode2 < 5.0, which has incompatible rxUi serialization with rxode2 >= 5.0.
Usage
test_nlmixr2_is_old_fit(xpdb)
Arguments
xpdb |
< |
Value
logical: TRUE if old incompatible fit, FALSE if compatible, NA if cannot determine
Logical instead of exception for xpose data check
Description
Logical instead of exception for xpose data check
Usage
test_xpdb(xpdb, check = "data")
Arguments
xpdb |
An xpose database object. |
check |
The 'xpdb' slot to be checked, can be 'data', 'files', 'summary', 'special', 'code', a file name, or 'FALSE'. IF 'FALSE' the slot test will be skipped. |
Typical processing for plots of 2 sets
Description
Typical processing for plots of 2 sets
Usage
two_set_dots(xpdb_s, ..., .inorder = FALSE, envir = parent.frame())
Arguments
xpdb_s |
< |
... |
< |
.inorder |
< |
envir |
Where to assign |
Details
Note that this function does not return valid xpdb-like objects (<xpose_data>
or <xp_xtras>). The necessary objects for most functions can be retrieved using
mod1$xpdb and mod2$xpdb.
Value
Into environment specified by envir, <xpose_set_item> mod1 and mod2
Translate values to levels
Description
This is intended to be used as a convenience function in plotting where levels are set for some variable.
Usage
val2lvl(vals, lvl_tbl = NULL)
Arguments
vals |
vector of values associated with levels in |
lvl_tbl |
tibble of levels |
Value
A vector of levels corresponding to the input vector. If
lvl_tbl carries an ordered attribute set to TRUE (see
set_var_levels()'s .ordered argument and lvl_inord()), the
result is an ordered factor.
An xp_xtras example of the discrete-time Markov model of categorical vismodegib data
Description
The referenced work presents two alternative modeling approaches for muscle spasm response to vismodegib. This is a fit of the provided discrete-time Markov model to the 50 participant mock data.
Usage
vismo_dtmm
Format
xp_xtras
An xp_xtras object.
Source
Derived from sup-0009 and sup-0010 from the reference.
References
Lu, T., Yang, Y., Jin, J.Y. and Kågedal, M. (2020), Analysis of Longitudinal-Ordered Categorical Data for Muscle Spasm Adverse Event of Vismodegib: Comparison Between Different Pharmacometric Models. CPT Pharmacometrics Syst. Pharmacol., 9: 96-105. doi:10.1002/psp4.12487
Examples
# To establish as a complete categorical DV example:
vismo_dtmm <- vismo_dtmm %>%
set_var_types(.problem=1, catdv=DV, dvprobs=matches("^P\\d+$")) %>%
set_dv_probs(.problem=1, 0~P0,1~P1,ge(2)~P23)
An xp_xtras example of the proportional odds categorical vismodegib model
Description
The referenced work presents two alternative modeling approaches for muscle spasm response to vismodegib. This is a fit of the provided proportional odds model to the 50 participant mock data.
Usage
vismo_pomod
Format
xp_xtras
An xp_xtras object.
Source
Derived from sup-0009 and sup-0010 from the reference.
References
Lu, T., Yang, Y., Jin, J.Y. and Kågedal, M. (2020), Analysis of Longitudinal-Ordered Categorical Data for Muscle Spasm Adverse Event of Vismodegib: Comparison Between Different Pharmacometric Models. CPT Pharmacometrics Syst. Pharmacol., 9: 96-105. doi:10.1002/psp4.12487
Examples
# To establish as a complete categorical DV example:
vismo_pomod <- vismo_pomod %>%
set_var_types(.problem=1, catdv=DV, dvprobs=matches("^P\\d+$")) %>%
set_dv_probs(.problem=1, 0~P0,1~P1,ge(2)~P23)
A tibble of mock data used for fitting vismodegib models
Description
The referenced work presents two alternative modeling approaches for muscle spasm response to vismodegib. There is a mock dataset for one person, and using the provided model a 50 participant mock dataset could be generated.
Usage
vismodegib
Format
tibble
An tibble.
Source
Generated using sup-0009 and sup-0010 from the reference.
References
Lu, T., Yang, Y., Jin, J.Y. and Kågedal, M. (2020), Analysis of Longitudinal-Ordered Categorical Data for Muscle Spasm Adverse Event of Vismodegib: Comparison Between Different Pharmacometric Models. CPT Pharmacometrics Syst. Pharmacol., 9: 96-105. doi:10.1002/psp4.12487
Ensure consistent style with GGally functions
Description
Ensure consistent style with GGally functions
Usage
wrap_xp_ggally(fn, xp_theme, ...)
Arguments
fn |
< |
xp_theme |
theme to use |
... |
< |
Value
ggplot2 function
Updated version of the xpose4 theme
Description
Updated version of the xpose4 theme
Usage
xp4_xtra_theme()
Value
An xpose theme object with xpose4 color palette
Convenience function for ingesting a bbr model into xpose and xpose.xtras
Description
bbr is a Metrum Research
Group package for managing NONMEM modeling workflows via bbi. It is not
distributed on CRAN (see Additional_repositories in this package's
DESCRIPTION for where to obtain it).
Reading a bbr-managed model into xpose/xpose.xtras normally requires
manually reconstructing the output file path from the model object, e.g.
xpose::xpose_data( file = file.path(bbr::get_output_dir(mod), paste0(bbr::get_model_id(mod), ".lst")) ) |> as_xp_xtras()
xp_from_bbr() wraps that pipeline.
Usage
xp_from_bbr(.mod, ..., .use_bbr_descr = TRUE)
Arguments
.mod |
< |
... |
Passed to |
.use_bbr_descr |
< |
Value
An <xp_xtras> object
See Also
Examples
if (requireNamespace("bbr", quietly = TRUE)) {
# Build a bbr-style model directory from the bundled pheno_saemimp example
src_dir <- system.file("pheno_saemimp", package = "xpose.xtras")
mod_dir <- tempfile("xp_from_bbr_ex")
dir.create(mod_dir)
file.copy(file.path(src_dir, "run18.mod"), file.path(mod_dir, "18.mod"))
out_dir <- file.path(mod_dir, "18")
dir.create(out_dir)
out_files <- setdiff(list.files(src_dir, pattern = "^run18\\."), "run18.mod")
for (f in out_files) {
file.copy(
file.path(src_dir, f),
file.path(out_dir, paste0("18.", sub("^run18\\.", "", f)))
)
}
# bbr considers a run finished once bbi has written this file
writeLines("{}", file.path(out_dir, "bbi_config.json"))
mod <- bbr::new_model(file.path(mod_dir, "18"), .description = "Phenobarbital SAEM model")
xp_from_bbr(mod)
}
xp_var Method
Description
To add a small amount of functionality to <xp_var>,
this method was created.
Usage
xp_var(xpdb, .problem, col = NULL, type = NULL, silent = FALSE)
## Default S3 method:
xp_var(xpdb, .problem, col = NULL, type = NULL, silent = FALSE)
## S3 method for class 'xp_xtras'
xp_var(xpdb, .problem, col = NULL, type = NULL, silent = FALSE)
Arguments
xpdb |
An xpose database object. |
.problem |
The $problem number to be used. |
col |
The column name to be searched in the index. Alternative to arg 'type'. |
type |
The type of column to searched in the index. Alternative to 'col'. |
silent |
Should the function be silent or return errors. |
Value
A tibble of identified variables.
Extra theme defaults
Description
Adds aesthetics for plot components used in this package.
Usage
xp_xtra_theme(base_on = NULL)
Arguments
base_on |
|
Details
This package attempts to generate a consistent
theme even if users are working with a highly
customized xp_theme. There is are only a few
hard-coded aesthetics, and the rest are derived from
existing aesthetics in base_on, which defaults to
the default from xpose.
Only a few options are worth noting. In <xplot_pairs>
(and functions using it), the aesthetics for GGally-specific
elements like barDiag are defined as gga(element)_(aesthetic).
The labeller for pairs plots is also changed from the de facto default
label_both to label_value, but any labeller can be provided as
pairs_labeller.
Value
An xpose theme object
An example xpose_set object
Description
A set of identical xpdb objects to demo various features of xpose.xtras.
Usage
xpdb_set
Format
xpose_set
An xpose_set object of length 4 with a single lineage.
Source
Assembled from the xpdb_ex_pk object in the xpose package.
An example xp_xtras object
Description
The <xpdb_ex_pk> object converted to xp_xtras. For examples.
Usage
xpdb_x
Format
xp_xtras
An xp_xtras object with no extra data filled.
Source
Assembled from the xpdb_ex_pk object in the xpose package.
Generic binned trend plotting function
Description
Following the xpose design pattern, this is a generic template
(analogous to xplot_boxplot() or xplot_pairs()) for rendering
already-summarized/binned data as connected points and/or lines across
a (typically discrete, possibly ordered) x variable. It is not tied to
any particular binning or summarization logic – callers are expected
to shape their data (eg via opt's post_processing) and build a named
implementation on top of it (eg catdv_vs_occ()) rather than calling
it directly for everyday use.
Usage
xplot_binned(
xpdb,
mapping = NULL,
group = "variable",
type = "pl",
xscale = "discrete",
yscale = "continuous",
title = NULL,
subtitle = NULL,
caption = NULL,
tag = NULL,
plot_name = "binned",
gg_theme,
xp_theme,
opt,
quiet,
...
)
Arguments
xpdb |
< |
mapping |
|
group |
Column name distinguishing multiple summarized series (eg
a |
type |
String setting the type of plot to be used: point |
xscale |
Defaults to |
yscale |
Defaults to |
title |
Plot title |
subtitle |
Plot subtitle |
caption |
Plot caption |
tag |
Plot tag |
plot_name |
Metadata name of plot |
gg_theme |
As in |
xp_theme |
As in |
opt |
Processing options for fetched data |
quiet |
Silence extra debugging output |
... |
Additional aesthetics, passed to the |
Details
Unlike xpose::xplot_scatter()'s raw per-subject spaghetti plots,
xplot_binned() assumes the supplied data is already one row per
x/group combination (eg per occasion, per series) – it does no binning,
aggregation, or tidying of its own.
Value
The desired plot
Default xpose boxplot function
Description
Manually generate boxplots from an xpdb object.
Usage
xplot_boxplot(
xpdb,
mapping = NULL,
type = "bo",
xscale = "discrete",
yscale = "continuous",
orientation = "x",
group = "ID",
title = NULL,
subtitle = NULL,
caption = NULL,
tag = NULL,
plot_name = "boxplot",
gg_theme,
xp_theme,
opt,
quiet,
jitter_seed,
...
)
Arguments
xpdb |
< |
mapping |
|
type |
See Details. |
xscale |
Defaults to |
yscale |
Defaults to |
orientation |
Defaults to |
group |
Grouping for connecting lines through jitter |
title |
Plot title |
subtitle |
Plot subtitle |
caption |
Plot caption |
tag |
Plot tag |
plot_name |
Metadata name of plot |
gg_theme |
As in |
xp_theme |
As in |
opt |
Processing options for fetched data |
quiet |
Silence extra debugging output |
jitter_seed |
A numeric, optional seed to be used in jitters |
... |
Any additional aesthetics. |
Details
For type-based customization of plots:
-
bbox-whisker (using default quantiles) -
ppoints (fromgeom_dotplot) -
vviolin (fromgeom_violin) -
ooutliers (show outliers) -
lline through 0 (or as indicated inhline_yinterceptoryline_xintercept) -
ssmooth line (fromgeom_smooth) -
jjitter points (fromgeom_jitter) -
cconnecting lines for jitter points (fromgeom_path)
Value
The desired plot
Default xpose forest plot function
Description
Manually generate a forest-style plot (point + interval per category)
from an xpdb object. This is a generic, low-level renderer in the same
spirit as xplot_boxplot()/xpose::xplot_scatter(): it has no built-in knowledge
of covariate associations, prm_cov(), or any other specific data
source – it just draws a point + interval (and, per type, a
reference guide line) from whatever mapping/pre-fetched opt data
it's given. See cov_forest() for the covariate-association-specific
wrapper that prepares that mapping from prm_cov() and calls this
function to render it.
Usage
xplot_forest(
xpdb,
mapping = NULL,
type = "pi",
region = NULL,
orientation = "y",
xscale = "continuous",
yscale = "discrete",
title = NULL,
subtitle = NULL,
caption = NULL,
tag = NULL,
plot_name = "forest",
gg_theme,
xp_theme,
opt,
violin_opt,
quiet,
...
)
Arguments
xpdb |
< |
mapping |
|
type |
See Details. |
region |
< |
orientation |
Defaults to |
xscale |
Defaults to |
yscale |
Defaults to |
title |
Plot title |
subtitle |
Plot subtitle |
caption |
Plot caption |
tag |
Plot tag |
plot_name |
Metadata name of plot |
gg_theme |
As in |
xp_theme |
As in |
opt |
Processing options for fetched data (one row per category). |
violin_opt |
Processing options for the violin layer's data (one
row per draw), only used/required when |
quiet |
Silence extra debugging output |
... |
Any additional aesthetics, or overrides for the reference
line (eg |
Details
For type-based customization of plots:
-
ppoint (fromgeom_point) – the effect estimate -
iinterval (fromgeom_linerange) – the confidence/credible interval -
lreference line through the theme'svline_xintercept/hline_yintercept(0by default; a ratio-style forest plot will typically override this to1, seecov_forest()) -
vviolin/density (fromgeom_violin), showing the distribution behind an interval (eg simulation draws) – requiresviolin_optand aviolin_x/violin_ymapping, see above -
rshaded reference region (fromgeom_rect) spanningregion(defaultc(0.8, 1.25)), eg a bioequivalence-style "no relevant effect" band; drawn behind every other layer
Value
The desired plot
Generic heatmap plotting function
Description
Following the xpose design pattern, this is a generic template
(analogous to xplot_boxplot() or xplot_pairs()) for rendering a
numeric matrix as a themed tile heatmap with cell value labels. It is not
tied to any particular data source; callers are expected to build a named
implementation on top of it (eg, cormat() for parameter
correlation/covariance matrices) rather than calling it directly for
everyday use.
Usage
xplot_heatmap(
xpdb,
mat,
digits = 3,
limits = NULL,
midpoint = 0,
legend_name = "Value",
title = NULL,
subtitle = NULL,
caption = NULL,
tag = NULL,
plot_name = "heatmap",
gg_theme,
xp_theme,
quiet,
...
)
Arguments
xpdb |
< |
mat |
A numeric matrix with row and column names. |
digits |
Number of significant digits to display in cell labels |
limits |
Fill scale limits, as |
midpoint |
Fill scale midpoint |
legend_name |
Fill scale/legend title |
title |
Plot title |
subtitle |
Plot subtitle |
caption |
Plot caption |
tag |
Plot tag |
plot_name |
Metadata name of plot |
gg_theme |
As in |
xp_theme |
As in |
quiet |
Silence extra debugging output |
... |
Additional aesthetics, passed to the |
Value
The desired plot
Examples
m <- matrix(c(1, 0.5, 0.5, 1), nrow = 2, dimnames = list(c("A", "B"), c("A", "B")))
xplot_heatmap(xpdb_x, m, quiet = TRUE)
Wrapper around ggpairs
Description
Following the xpose design pattern to derive <ggpairs> plots.
Established xplot_ are used to generate parts of the grid.
Usage
xplot_pairs(
xpdb,
mapping = NULL,
cont_opts = list(group = "ID", guide = FALSE, type = "ps"),
dist_opts = list(guide = FALSE, type = "hr"),
cat_opts = list(type = "bo", log = NULL),
contcont_opts = list(other_fun = NULL, stars = FALSE, digits = reportable_digits(xpdb),
title = "Pearson Corr"),
catcont_opts = list(other_fun = NULL, stars = FALSE, digits = reportable_digits(xpdb),
title = "Spearman rho"),
catcat_opts = list(use_rho = TRUE),
title = NULL,
subtitle = NULL,
caption = NULL,
tag = NULL,
plot_name = "pairs",
gg_theme,
xp_theme,
opt,
quiet,
progress = rlang::is_interactive() && quiet,
switch = NULL,
...
)
Arguments
xpdb |
< |
mapping |
|
cont_opts |
List of options to pass to |
dist_opts |
List of options to pass to |
cat_opts |
List of options to pass to |
contcont_opts |
List of options to pass to |
catcont_opts |
List of options to pass to |
catcat_opts |
A list with |
title |
Plot title |
subtitle |
Plot subtitle |
caption |
Plot caption |
tag |
Plot tag |
plot_name |
Metadata name of plot |
gg_theme |
As in |
xp_theme |
As in |
opt |
Processing options for fetched data |
quiet |
Silence extra debugging output |
progress |
Show a progress bar as the plot is generated? |
switch |
Passed to |
... |
Ignored |
Details
There is only limited control over the underlying ggpairs() call given
the need to address abstractions in GGally and xpose. However, users
can modify key display features. For scatter, distribution and boxplots,
the type option is directly forwarded to the user. For upper elements of the matrix,
users can modify features of the text displayed or supply some other
function entirely (other_fun).
_opts lists are consumed with <modifyList> from the default,
so there is no need to declare preferences that align with the default if updating
a subset.
Value
specified pair plot
Default xpose ROC plot function
Description
Manually generate ROCs from an xpdb object.
Usage
xplot_rocplot(
xpdb,
mapping = NULL,
type = "c",
guide = TRUE,
xscale = "continuous",
yscale = "continuous",
group = NULL,
title = NULL,
subtitle = NULL,
caption = NULL,
tag = NULL,
plot_name = "xplot_rocplot",
gg_theme,
xp_theme,
opt,
quiet,
thres_fixed = 0.5,
like_col = NULL,
obs_col = NULL,
obs_target = NULL,
auc_sprintf = "AUC: %.3f",
...
)
Arguments
xpdb |
< |
mapping |
|
type |
See Details. |
guide |
Should the guide (e.g. unity line) be displayed. |
xscale |
Defaults to |
yscale |
Defaults to |
group |
Grouping for curves or points |
title |
Plot title |
subtitle |
Plot subtitle |
caption |
Plot caption |
tag |
Plot tag |
plot_name |
Metadata name of plot |
gg_theme |
As in |
xp_theme |
As in |
opt |
Processing options for fetched data |
quiet |
Silence extra debugging output |
thres_fixed |
Fixed threshold value for space |
like_col |
Column for likelihood/probability value |
obs_col |
Column for observed value |
obs_target |
Target observed value for likelihood |
auc_sprintf |
Format to apply to AUC label |
... |
Any additional aesthetics. |
Details
For type-based customization of plots:
-
cROC curve (usinggeom_path) -
kKey points on ROC curve (where on curve the threshold isthres_fixed) (usinggeom_point) -
pROC space points (usinggeom_point) -
tROC space text (usinggeom_text) -
aAUC in bottom right (usinggeom_label)
Value
The desired plot
Generate a set of xpdb objects
Description
This function generates a set of xpose data (xpdb) objects that
can be used to define relationships between models. The
Usage
xpose_set(..., .relationships = NULL, .as_ordered = FALSE)
Arguments
... |
< |
.relationships |
< |
.as_ordered |
< |
Details
Beyond just a list of xpdb objects, an xpose_set adds hierarchical information.
When using .relationships, these should be expressed as tilde formulas, where the left-hand side is
children and the right and side is parents. In the simplest case, this would be child ~ parent, but a child can have multiple parents. This
syntax expects that the names for models is either declared as argument names in the call, or that the
variable names are directly used (i.e., not spliced or passed as an unnamed list).
Value
A list of class xpose_set
Examples
data("xpdb_ex_pk", package = "xpose")
# Arbitrary copy
xpdb_ex_pk2 <- xpdb_ex_pk
# Simplest call
set1 <- xpose_set(xpdb_ex_pk, xpdb_ex_pk2)
# With predefined relationships
set2 <- xpose_set(xpdb_ex_pk, xpdb_ex_pk2,
.relationships = list(xpdb_ex_pk2 ~ xpdb_ex_pk)
)
# Alternative predefined relationships
set2b <- xpose_set(xpdb_ex_pk, xpdb_ex_pk2,
.as_ordered = TRUE
)
# With custom labels
set3 <- xpose_set(mod1 = xpdb_ex_pk, mod2 = xpdb_ex_pk2,
.relationships = list(mod2 ~ mod1)
)
# Alternative set3 using dyanmic dots
mod_list <- list(
mod1 = xpdb_ex_pk,
mod2 = xpdb_ex_pk2
)
mod_rels <- list(
mod2 ~ mod1
)
set3b = xpose_set(!!!mod_list, .relationships = mod_rels)
Determine lineage within a set
Description
Determine lineage within a set
Usage
xset_lineage(xpdb_s, ..., .spinner = NULL)
Arguments
xpdb_s |
< |
... |
< |
.spinner |
Set to |
Details
This function uses a not-especially-optimized tree-searching algorithm
to determine the longest lineage starting from whatever is treated as
the base model. It is based loosely on <pluck_depth>,
but the values at each depth are maintained.
As such, for larger sets this function and, more importantly,
functions that use it may take some time.
Value
<character> vector of c('base', 'base child', 'base grandchild', ...) or list thereof, depending on dots arguments.
Examples
xset_lineage(xpdb_set)
set_base_model(xpdb_set, fix1) %>%
xset_lineage()
xset_lineage(xpdb_set, fix1)
Waterfall plot
Description
Generic function primarily used with wrappers targeting types of values changed between two models.
Usage
xset_waterfall(
xpdb_s,
...,
.inorder = FALSE,
type = "bh",
.cols = NULL,
max_nind = 0.7,
scale_diff = TRUE,
show_n = TRUE,
title = NULL,
subtitle = NULL,
caption = NULL,
tag = NULL,
plot_name = "waterfall",
opt,
facets = NULL,
facet_scales = "free_x",
.problem,
.subprob,
.method,
quiet
)
Arguments
xpdb_s |
< |
... |
See < |
.inorder |
See < |
type |
See Details. |
.cols |
< |
max_nind |
If less than 1, the percentile of absolute change values above which to plot. If above 1, the absolute number of subjects is included. To show all, use an extreme positive number like 9999. |
scale_diff |
< |
show_n |
< |
title |
Plot title |
subtitle |
Plot subtitle |
caption |
Plot caption |
tag |
Plot tag |
plot_name |
Metadata name of plot |
opt |
User-specified data options. Only some of these will be used. |
facets |
< |
facet_scales |
< |
.problem |
The problem to be used, by default returns the last one. |
.subprob |
The subproblem to be used, by default returns the last one. |
.method |
The estimation method to be used, by default returns the last one. |
quiet |
Silence extra debugging output |
Details
For type-based customization of plots:
-
bbar plot (fromgeom_bar) -
hhline at 0 (fromgeom_hline) -
ttext of change value (fromgeom_text)
Value
The desired plot