## rxode2 5.1.7 using 2 threads (see ?getRxThreads)
## no cache: create with `rxCreateCache()`
Introduction
This briefly describes the syntax used to define models that
rxode2 will translate into R-callable compiled code. It
also describes the communication of variables between R and
the rxode2 modeling specification.
Creating rxode2 models
The ODE-based model specification may be coded inside four places:
- Inside a
rxode2({})block statements:
library(rxode2)
mod <- rxode2({
# simple assignment
C2 <- centr/V2
# time-derivative assignment
d/dt(centr) <- F*KA*depot - CL*C2 - Q*C2 + Q*C3;
})- Inside a
rxode2("")string statement:
mod <- rxode2("
# simple assignment
C2 <- centr/V2
# time-derivative assignment
d/dt(centr) <- F*KA*depot - CL*C2 - Q*C2 + Q*C3;
")- In a file name to be loaded by rxode2:
writeLines("
# simple assignment
C2 <- centr/V2
# time-derivative assignment
d/dt(centr) <- F*KA*depot - CL*C2 - Q*C2 + Q*C3;
", "modelFile.rxode2")
mod <- rxode2(filename='modelFile.rxode2')
unlink("modelFile.rxode2")- In a model function which can be parsed by
rxode2:
mod <- function() {
model({
# simple assignment
C2 <- centr/V2
# time-derivative assignment
d/dt(centr) <- F*KA*depot - CL*C2 - Q*C2 + Q*C3;
})
}
mod <- rxode2(mod) # or simply mod() if the model is at the end of the function
# These model functions often have residual components and initial
# (`ini({})`) conditions attached as well. For example the
# theophylline model can be written as:
one.compartment <- function() {
ini({
tka <- 0.45 # Log Ka
tcl <- 1 # Log Cl
tv <- 3.45 # 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)
d/dt(depot) = -ka * depot
d/dt(center) = ka * depot - cl / v * center
cp = center / v
cp ~ add(add.sd)
})
}
# after parsing the model
mod <- one.compartment()For the block statement, character string or text file an internal
rxode2 compilation manager translates the ODE system into
C, compiles it and loads it into the R session. The call to
rxode2 produces an object of class rxode2
which consists of a list-like structure (environment) with various
member functions.
For the last type of model (a model function), a call to
rxode2 creates a parsed rxode2 ui that can be
translated to the rxode2 compilation model.
mod$simulationModel
# or
mod$simulationIniModelThis is the same type of function required for nlmixr2
estimation and can be extended and modified by model piping. For this
reason will be focused on in the documentation.
Syntax
This basic model specification consists of one or more statements
optionally terminated by semi-colons ; and optional
comments (comments are delimited by # and an
end-of-line).
A block of statements is a set of statements delimited by curly
braces, { ... }.
Statements can be either assignments, conditional
if/else if/else,
while loops (can be exited by break), special
statements, or printing statements (for debugging/testing).
Assignment statements can be:
simple assignments, where the left hand is an identifier (i.e., variable). This includes string assignments
special time-derivative assignments, where the left hand specifies the change of the amount in the corresponding state variable (compartment) with respect to time e.g.,
d/dt(depot):special initial-condition assignments where the left hand specifies the compartment of the initial condition being specified, e.g.
depot(0) = 0special model event changes including bioavailability (
f(depot)=1), lag time (alag(depot)=0), modeled rate (rate(depot)=2) and modeled duration (dur(depot)=2). An example of these model features and the event specification for the modeled infusions the rxode2 data specification is found in rxode2 events vignette.special change point syntax, or model times. These model times are specified by
mtime(var)=timespecial Jacobian-derivative assignments, where the left hand specifies the change in the compartment ode with respect to a variable. For example, if
d/dt(y) = dy, then a Jacobian for this compartment can be specified asdf(y)/dy(dy) = 1. There may be some advantage to obtaining the solution or specifying the Jacobian for very stiff ODE systems. However, for the few stiff systems we tried with LSODA, this actually slightly slowed down the solving.Special string value declarations which tell what values a string variable will take within a
rxode2solving structure. These values will then cause a factor to be created for this variable on solving therxode2model. As such, they are declared in much the same way asR, that is:labels(a) <- c("a1", "a2").
Note that assignment can be done by =,
<- or ~.
When assigning with the ~ operator, the simple
assignments and time-derivative assignments
will not be output. Note that with the rxode2 model
functions assignment with ~ can also be overloaded with a
residual distribution specification.
Special statements can be:
Compartment declaration statements, which can change the default dosing compartment and the assumed compartment number(s) as well as add extra compartment names at the end (useful for multiple-endpoint nlmixr models); These are specified by
cmt(compartmentName)Parameter declaration statements, which can make sure the input parameters are in a certain order instead of ordering the parameters by the order they are parsed. This is useful for keeping the parameter order the same when using 2 different ODE models. These are specified by
param(par1, par2,...)Variable interpolation statements, which tells the interpolation for specific covariates. These include
locf(cov1, cov2, ...)for last observation carried forward,nocb(cov1, cov2, ...)for next observation carried backward,linear(cov1, cov2, ...)for linear interpolation andmidpoint(cov1, cov2, ...)for midpoint interpolation.
An example model is shown below:
# simple assignment
C2 <- centr/V2
# time-derivative assignment
d/dt(centr) <- F*KA*depot - CL*C2 - Q*C2 + Q*C3;
Expressions in assignment and if statements can be
numeric or logical.
Numeric expressions can include the following numeric operators
+, -, *, /, ^, %% and those mathematical functions defined
in the C or the R math libraries (e.g., fabs,
exp, log, sin,
abs).
You may also access the R’s functions in the R
math libraries, like lgammafn for the log gamma
function.
The rxode2 syntax is case-sensitive, i.e.,
ABC is different than abc, Abc,
ABc, etc.
Identifiers
Like R, Identifiers (variable names) may consist of one or more
alphanumeric, underscore _ or period .
characters, but the first character cannot be a digit or underscore
_.
Identifiers in a model specification can refer to:
- State variables in the dynamic system (e.g., compartments in a pharmacokinetics model).
- Implied input variable,
t(time),tlast(last time point), andpodo(oral dose, in the undocumented case of absorption transit models). - Special constants like
pior R’s predefined constants. - Model parameters (e.g.,
karate of absorption,CLclearance, etc.) - Others, as created by assignments as part of the model specification; these are referred as LHS (left-hand side) variable.
Currently, the rxode2 modeling language only recognizes
system state variables and “parameters”, thus, any values that need to
be passed from R to the ODE model (e.g., age) should be
either passed in the params argument of the integrator
function rxSolve() or be in the supplied event
data-set.
There are certain variable names that are in the rxode2
event tables. To avoid confusion, the following event table-related
items cannot be assigned, or used as a state but can be accessed in the
rxode2 code:
cmtdvidaddlssamtdurrateRprintfprintprintfid
However the following variables are cannot be used in a model specification:
evidii
Sometimes rxode2 generates variables that are fed back to rxode2.
Similarly, nlmixr2 generates some variables that are used in nlmixr
estimation and simulation. These variables start with the either the
rx or nlmixr prefixes. To avoid any problems,
it is suggested to not use these variables starting with either the
rx or nlmixr prefixes.
Logical Operators
Logical operators support the standard R operators ==,
!= >= <= >
and <. Like R these can be in if() or
while() statements, ifelse() expressions.
Additionally they can be in a standard assignment. For instance, the
following is valid:
cov1 = covm*(sexf == "female") + covm*(sexf != "female")
Notice that you can also use character expressions in comparisons.
This convenience comes at a cost since character comparisons are slower
than numeric expressions. Unlike R, as.numeric or
as.integer for these logical statements is not only not
needed, but will cause an syntax error if you try to use the
function.
Supported functions
All the supported functions in rxode2 can be seen with the
rxSupportedFuns().
A brief description of the built-in functions are in the following table:
Note that lag(cmt) = is equivalent to
alag(cmt) = and not the same as = lag(wt)
Reserved keywords
There are a few reserved keywords in a rxode2 model. They are in the following table:
Note that rxFlag will always output 11 or
calc_lhs since that is where the final variables are
calculated, though you can tweak or test certain parts of
rxode2 by using this flag.
Residual functions when using rxode2 functions
In addition to ~ hiding output for certain types of
output, it also is used to specify a residual output or endpoint when
the input is an rxode2 model function (that includes the
residual in the model({}) block).
These specifications are of the form:
var ~ add(add.sd)Indicating the variable var is the variable that
represents the individual central tendencies of the model and it also
represents the compartment specification in the data-set.
You can also change the compartment name using the |
syntax, that is:
var ~ add(add.sd) | cmtIn the above case var represents the central tendency
and cmt represents the compartment or dvid
specification.
Transformations
For normal and related distributions, you can apply the transformation on both sides by using some keywords/functions to apply these transformations.
By default for the likelihood for all of these transformations is calculated on the untransformed scale.
For bounded variables like logit-normal or probit-normal the low and high values are defaulted to 0 and 1 if missing.
For models where you wish to have a proportional model on one of
these transformation you can replace the standard deviation with
NA
To allow for more transformations, lnorm(),
probitNorm() and logitNorm() can be combined
the variance stabilizing yeoJohnson() transformation.
Normal and t-related distributions
For the normal and t-related distributions, we wanted to keep the
ability to use skewed distributions additive and proportional in the
t/cauchy-space, so these distributions are specified differently in
comparison to the other supported distributions within
nlmixr2:
Note that with the normal and t-related distributions
nlmixr2 will calculate cwres and
npde under the normal assumption to help assess the
goodness of the fit of the model.
Also note that the +dnorm() is mostly for testing
purposes and will slow down the estimation procedure in
nlmixr2. We suggest not adding it (except for explicit
testing). When there are multiple endpoint models that mix non-normal
and normal distributions, the whole problem is shifted to a
log-likelihood method for estimation in nlmixr2.
Notes on additive + proportional models
There are two different ways to specify additive and proportional models, which we will call combined1 and combined2, the same way that Monolix calls the two distributions (to avoid between software differences in naming).
The first, combined1, assumes that the additive and proportional differences are on the standard deviation scale, or:
y=f+(a+b* f^c)*err
The second, combined2, assumes that the additive and proportional differences are combined on a variance scale:
y=f+*err
The default in nlmixr2/rxode2 if not
otherwise specified is combined2 since it mirrors how
adding 2 normal distributions in statistics will add their variances
(not the standard deviations). However, the combined1
can describe the data possibly even better than
combined2 so both are possible options in
rxode2/nlmixr2.
Autocorrelated residuals (ar())
Adding ar(cor) to a normal residual makes successive
residuals of the same endpoint follow a continuous-time AR(1)
process:
cp ~ add(add.sd) + ar(ar1.cor)Here ar1.cor is the lag-one correlation and must be in
[0, 1). The correlation between two residuals separated by
a time gap dt is cor^dt, so irregular sampling
is handled directly and the marginal (stationary) residual variance is
unchanged; the first observation of each subject/endpoint uses the
marginal distribution. ar() combines with
add()/prop() normal residuals and uses the
same | cmt endpoint syntax as the other residual
functions.
The ar() specification is identical in
rxode2 and nlmixr2: the same model line
simulates the autocorrelated residual in rxode2 and
estimates the correlation in nlmixr2 (the nlm,
focei/foce and saem families
support it; fo, foi, nlme and
nls do not). See Karlsson et al. (1995) for the
continuous-time AR(1) residual model.
Distributions of known likelihoods
For residuals that are not related to normal, t-distribution or cauchy, often the residual specification is of the form:
cmt ~ dbeta(alpha, beta)Where the compartment specification is on the left handed side of the specification.
For generalized likelihood you can specify:
Ordinal likelihoods
Finally, ordinal likelihoods/simulations can be specified in 2 ways. The first is:
err ~ c(p0, p1, p2)Here err represents the compartment and p0
is the probability of being in a specific category:
| Category | Probability |
|---|---|
| 1 | p0 |
| 2 | p1 |
| 3 | p2 |
| 4 | 1-p0-p1-p2 |
It is up to the model to ensure that the sum of the p
values are less than 1. Additionally you can write an
arbitrary number of categories in the ordinal model described above.
It seems a little off that p0 is the probability for
category 1 and sometimes scores are in non-whole numbers.
This can be modeled as follows:
err ~ c(p0=0, p1=1, p2=2, 3)Here the numeric categories are specified explicitly, and the probabilities remain the same:
| Category | Probability |
|---|---|
| 0 | p0 |
| 1 | p1 |
| 2 | p2 |
| 3 | 1-p0-p1-p2 |
General table of supported residual distributions
In general all the that are supported are in the following table
(available in rxode2::rxResidualError)
Prior distributions in the ini({}) block
When an estimation method supports priors, the prior on a parameter
is given in the ini({}) block with:
prior(name) ~ dist(...)Because the statement names the parameter it applies to, prior lines
are order independent; they can be put anywhere in the
ini({}) block.
one.compartment <- function() {
ini({
tka <- 0.45
tcl <- log(c(0, 2.7, 100))
tv <- 3.45
add.sd <- c(0, 0.7)
eta.cl + eta.v ~ c(0.3,
0.01, 0.1)
eta.ka ~ 0.6
prior(tka) ~ dnorm(0, 10)
prior(tcl) ~ dnorm(1, 10)
prior(add.sd) ~ dcauchy(0, 5)
prior(eta.ka) ~ dgamma(2, 1)
prior(eta.cl, eta.v) ~ lkjCorr(2)
})
model({
ka <- exp(tka + eta.ka)
cl <- exp(tcl + eta.cl)
v <- exp(tv + eta.v)
d/dt(depot) <- -ka * depot
d/dt(center) <- ka * depot - cl / v * center
cp <- center / v
cp ~ add(add.sd)
})
}A prior can be put on:
- a population parameter, ie
prior(tka) - a single between subject variability term, ie
prior(eta.ka) - a whole covariance block, using one of the matrix-valued
distributions, ie
prior(eta.cl, eta.v) ~ lkjCorr(2). The names given have to be exactly one block of the matrix.
The normal prior shorthand
Normal priors are by far the most common, so they also have a
shorthand that reuses the matrix syntax. Putting a population
parameter on the left of a ~ gives it a normal prior
with a zero mean and the given variance:
ini({
tka <- 1
tcl <- 3
tv <- 4
tka ~ 4 # tka ~ N(0, sd = 2)
tcl + tv ~ c(1, # (tcl, tv) ~ MVN(0, Sigma)
0.01, 1)
})The number on the right is a variance, so tka ~ 4 has a
standard deviation of 2. The value given with <- stays
the initial estimate; it is not the prior mean.
This is unambiguous because a name cannot be both a population parameter and an eta – that combination used to be a “duplicated parameter” error. A name that is not a population parameter still specifies an eta exactly as before.
Every matrix spelling works here, including the per-row line form, which builds up the block just as it does for etas:
tcl ~ 1
tv ~ c(0.01, 1)and the sd(), var(), cor(),
cov() and chol() transformations:
tcl + tv ~ sd(2,
0.5, 3) # variances of 4 and 9The matrix means exactly what it means for an eta block: the
off-diagonal is a covariance, not a correlation. A
prior block and an eta block written the same way give the same matrix,
so cor() is how you give a correlation here just as it is
there.
An uncorrelated block is simply independent normal priors, since that is what a multivariate normal with a diagonal covariance is. A zero variance is a point mass rather than a prior, so it is an error.
Priors on the omega values
The two NONMEM prior flavours want different things from an omega.
An NWPRI model gives the omega block degrees of freedom.
The scale matrix of the Wishart family is optional, because the block it
is put on already is that matrix, so only the degrees of
freedom are needed – this is the
$OMEGAP/$OMEGAPD pair:
It works on a 1x1 block as well, since an inverse Wishart of
dimension one is an inverse gamma. An improper
nu <= p - 1 is an error.
When every block shares the same degrees of freedom, a one-sided
~ sets them all at once instead of naming each block:
Each block is still checked individually, and naming a block as well is a duplicate rather than an override.
A TNPRI model instead puts a normal prior on the omega
elements, jointly with the thetas. Prepending om.
to a between subject variability names its omega element, so the normal
prior shorthand can be used on it:
ini({
eta.cl ~ 0.3
eta.v ~ 0.1
om.eta.cl ~ 0.01 # normal prior on the omega element of eta.cl
om.eta.v ~ 0.04
})The omega itself is untouched; only the prior is added. Correlated
omega priors work the same way, including the per-row line form. An
om. name has to match a real between subject variability –
it never quietly creates one.
Naming the eta directly means the same thing, so
prior(om.eta.cl) and prior(eta.cl) are
interchangeable. The om. spelling exists so the shorthand
has a name to put on the left of a ~, since
eta.cl ~ ... already means the omega value itself.
Prior distribution names
There are three spellings of every distribution, and all of them are accepted:
- the R name, when R parameterizes the distribution
the same way ‘Stan’ does –
dnorm(),dlnorm(),dgamma(),dbeta(),dcauchy(),dunif() - the camelCase name, which is the ‘Stan’ name
written the way the rest of the package is written –
invWishart(),lkjCorr(),studentT() - the ‘Stan’ name itself –
inv_wishart(),lkj_corr(),student_t()
The canonical one, which is what gets stored on the
iniDf and printed back, is the R name where there is a
faithful one and the camelCase name otherwise. The arguments may be
given positionally or by name, so these are all the same prior:
dt() is deliberately not accepted as a
spelling of studentT(): R’s dt() is the
standardized (or noncentral) t, while
studentT(nu, mu, sigma) (the ‘Stan’ student_t)
is a location-scale t, so treating them as the same would silently
change the prior. Use studentT() with its own
parameterization.
The full list of supported distributions, including the ‘Stan’ name
for each, is returned by lotri::lotriPriorDists().
Bounds and truncated priors
The bounds are not repeated in the prior; they come from the parameter itself. A parameter that is already bounded below by zero therefore gets a half distribution:
The prior is checked against those bounds, so putting a distribution with positive support on a parameter that allows negative values is an error.
Where the prior is stored
Priors are kept in the prior column of the model’s
$iniDf and are printed back as part of the
ini({}) block, so they survive printing and piping.
A prior you specify is never silently dropped. An estimation method that cannot use priors is expected to reject such a model rather than quietly ignore the prior, and rxode2 supplies the assertions for that:
-
assertRxUiNoPriors()– for a method that cannot use priors at all; a model that specifies one is an error -
assertRxUiNormalPriors()– for a method that supports priors but only normal ones. That coversdnorm()/normal(),stdNormal(), and themultiNormal()family, which is what the shorthand above produces for correlated parameters. Anything else, including a covariance matrix prior such aslkjCorr()orinvWishart(), is an error -
assertRxUiNoOmegaDf()– for a method that cannot use prior degrees of freedom on an omega block, ie theNWPRIform above -
assertRxUiNoOmegaNormalPriors()– for a method that can put a prior on an omega but only a Wishart one, ie it supportsNWPRIbut notTNPRI
A method that implements priors asks instead of asserts. The
predicates return TRUE/FALSE rather than
throwing:
-
testRxUiPriors()– does the model specify any prior at all -
testRxUiNormalPriors()– is every prior a normal one -
testRxUiOmegaDf()– does an omega carry degrees of freedom (NWPRI) -
testRxUiOmegaNormalPriors()– does an omega carry a normal prior (TNPRI)
The last two are mutually exclusive: an omega prior is either degrees of freedom or a normal prior, never both, and giving both is an error at specification time. So a method can branch on which one it got.
rxUiPriors() returns the priors themselves –
name, prior,
neta1/neta2 (NA for a population
parameter) and the parameter’s lower/upper,
which is what a truncated prior needs for its bounds.
So if a method silently ignored your prior, that is a bug in the method, not expected behaviour.
Simulating from the priors
rxSolve() uses the priors for its uncertainty
simulation, which is what NONMEM does with $PRIOR NWPRI and
$PRIOR TNPRI. Nothing extra has to be turned on: a model
that carries priors uses them whenever variability is being simulated,
that is when nStud is greater than one (or whatever
simVariability forces).
one.cmt <- function() {
ini({
tka <- 0.45
tcl <- 1
tv <- 3.45
eta.cl + eta.v ~ c(0.3,
0.01, 0.1)
eta.ka ~ 0.6
add.sd <- 0.7
tka ~ 0.01 # normal prior on tka
prior(eta.cl, eta.v) ~ invWishart(20) # degrees of freedom, per block
prior(eta.ka) ~ invWishart(4)
})
model({
ka <- exp(tka + eta.ka)
cl <- exp(tcl + eta.cl)
v <- exp(tv + eta.v)
linCmt() ~ add(add.sd)
})
}
s <- rxSolve(one.cmt, ev, nSub = 10, nStud = 100)
s$thetaMat # the per study population parameter draws
s$omegaList # the per study omega, one draw per study
Each omega block is drawn with its own degrees of
freedom, which the single dfSub argument cannot express –
above, the 2x2 block is drawn with 20 and the 1x1 with 4. A block with
no prior is left at its point estimate. dfWishart() helps
pick a degrees of freedom that matches a target relative standard
error.
The prior mean is the estimate
A draw is added to the value the model already gives, so a normal
prior on a population parameter has to be centered on its estimate, and
one on an omega element on that omega value. tka ~ 0.01 is
exactly that – the number is the variance and the mean comes from
tka <- 0.45. Writing a prior centered somewhere else is
an error rather than a simulation that quietly differs from what the
model says:
tka <- 0.45
prior(tka) ~ dnorm(0, 0.1)
#> Error: cannot simulate from the prior on 'tka' (dnorm(0, 0.1)): the
#> prior mean (0) is not the initial estimate (0.45)
A joint prior over the thetas and the omegas
A TNPRI variance matrix covers the population parameters
and the omega values together, with covariances between them. Prefix an
omega element with om. to name it, and put both in one
block:
tcl + om.eta.cl ~ c(0.02,
0.004, 0.005)
Drawn that way the omega is not guaranteed positive definite. A study
whose draw is not gets the whole joint vector redrawn, up to
priorPdRetry times (10 by default). If none of them is, the
nearest positive definite matrix of the kept draws is used and
rxSolve() warns – that projection lands on the boundary of
the positive definite cone, so those studies are not draws from the
stated prior. A model that reaches the fallback often wants a larger
priorPdRetry or a tighter prior.
Turning it off, and precedence
usePrior = FALSE ignores the priors and falls back to a
supplied thetaMat/dfSub;
usePrior = TRUE requires them and says why if it cannot
honor them. A thetaMat/dfSub carried in the
model’s meta block loses to the priors, with a warning. One
given at the call site wins over them instead, also with a warning – an
explicit argument is never silently discarded.
Prior simulation covers nested/occasion models (| id,
| occ). Each prior’s degrees of freedom go on the nesting
level that holds its block, and a level with no prior stays at its
estimate. One draw is shared across the occasions of a study, since the
level is drawn once.
A nesting level is drawn as a whole, so a prior has to cover its
level. A prior on part of a level – one of two independent blocks at
| id, say – is an error, because drawing the level would
redraw the other block too and correlate blocks the model declared
independent, and there is nowhere to put a second degrees of freedom.
Put the prior on the whole level instead.
Prior simulation does not yet cover a chunked solve
(file =/chunkSize =, rxode2 issue #1252),
which is a clear error rather than a solve that quietly drops the
prior.
A thetaMat that already carries the omegas
The same joint draw works without an ini({}) prior, for
a thetaMat that came from a covariance step.
nonmem2rx gives one directly, and so does a nlmixr2
fit:
mod <- nonmem2rx("run3.lst")
colnames(mod$thetaMat)
#> "t.CL" "GFRCL" ... "IIVCL" "omega1.2" "omega1.3" "IIVV1" ... "eps1" "sigma1.2"
rxSolve(mod, data.sim, nStud = 100, omegaSeparation = "tnpri")
omegaSeparation = "tnpri" says those entries are the
omega itself and should be drawn from the thetaMat jointly
with the thetas, instead of having their correlations redrawn by the
lkj/separation strategies – which discard the
off-diagonal entries the covariance step measured, and cannot carry a
covariance between a theta and an omega entry at all.
sigmaSeparation = "tnpri" does the same for the residual
entries.
Columns are matched to entries by name, in whichever spelling produced them:
| diagonal | off-diagonal | |
|---|---|---|
nlmixr2 fit $cov
|
om.eta.cl |
cov.eta.cl.eta.v |
nonmem2rx |
eta.cl |
omega1.2, omega.2.1
|
This is opt-in rather than automatic: an eta-named column already
means that eta’s variance under the existing separation strategy, so it
cannot change meaning on its own. omega has to be a matrix,
since the drawn entries are added to it.
Note on strings in rxode2
Strings are converted to double values inside of rxode2,
hence you can refer to them as an integer corresponding to the string
value or the string value itself. For covariates these are calculated on
the fly based on your data and you should likely not try this, though
you should be aware. For strings defined in the model, this is fixed and
both could be used.
For example:
if (APGAR == 10 || APGAR == 8 || APGAR == 9) {
tAPGAR <- "High"
} else if (APGAR == 1 || APGAR == 2 || APGAR == 3) {
tAPGAR <- "Low"
} else if (APGAR == 4 || APGAR == 5 || APGAR == 6 || APGAR == 7) {
tAPGAR <- "Med"
} else {
tAPGAR<- "Med"
}
Could also be replaced by:
if (APGAR == 10 || APGAR == 8 || APGAR == 9) {
tAPGAR <- "High"
} else if (APGAR == 1 || APGAR == 2 || APGAR == 3) {
tAPGAR <- "Low"
} else if (APGAR == 4 || APGAR == 5 || APGAR == 6 || APGAR == 7) {
tAPGAR <- "Med"
} else {
tAPGAR<- 3
}
Since "Med" is already defined
If you wanted you can pre-declare what levels it has (and the order) to give you better control of this:
levels(tAPGAR) <- c("Med", "Low", "High")
if (APGAR == 10 || APGAR == 8 || APGAR == 9) {
tAPGAR <- 3
} else if (APGAR == 1 || APGAR == 2 || APGAR == 3) {
tAPGAR <- 2
} else if (APGAR == 4 || APGAR == 5 || APGAR == 6 || APGAR == 7) {
tAPGAR <- 1
} else {
tAPGAR<- 1
}
You can see that the number changed since the declaration change the
numbers in each variable for tAPGAR. These
levels() statements need to be declared before the variable
occurs to ensure the numbering is consistent with what is declared.
Note
The ODE specification mini-language is parsed with the help of the open source tool , Plevyak (2015).
Example
f <- function() {
ini({
})
model({
# An rxode2 model specification (this line is a comment).
if(comed==0) { # concomitant medication (con-med)?
F <- 1.0 # full bioavailability w.o. con-med
} else {
F <- 0.80 # 20% reduced bioavailability
}
C2 <- centr/V2 # concentration in the central compartment
C3 <- peri/V3 # concentration in the peripheral compartment
# ODE describing the PK and PD
d/dt(depot) <- -KA*depot
d/dt(centr) <- F*KA*depot - CL*C2 - Q*C2 + Q*C3
d/dt(peri) <- Q*C2 - Q*C3
d/dt(eff) <- Kin - Kout*(1-C2/(EC50+C2))*eff
eff(0) <- 1
})
}Interface and data handling between R and the generated C code
Users specify which variables are the dynamic system’s state
variables via the d/dt(identifier) operator as part of the
model specification, and which are model parameters via the
params= argument in rxode2
solve() method:
m1 <- rxode2(model = ode, modName = "m1")
# model parameters -- a named vector is required
theta <-
c(KA=0.29, CL=18.6, V2=40.2, Q=10.5, V3=297, Kin=1, Kout=1, EC50=200)
# state variables and their amounts at time 0 (the use of names is
# encouraged, but not required)
inits <- c(depot=0, centr=0, peri=0, eff=1)
# qd1 is an eventTable specification with a set of dosing and sampling
# records (code not shown here)
solve(theta, event = qd1, inits = inits)The values of these variables at pre-specified time points are saved
during model fitting/integration and returned as part of the fitted
values (see the function et(), to define a set of time
points when to capture the values of these variables) and returned as
part of the modeling output.
The ODE specification mini-language is parsed with the help of the open source tool DParser, Plevyak (2015).
