Tutorials › Pharmacometric Workflows and Reproducible Modeling › Defining Models and Data in nlmixr2

Software Landscape and Interoperability · Tutorial 195 of 399

Defining Models and Data in nlmixr2

Learn to read and define an nlmixr2 model function and check that its one-compartment model and R data records describe the same analysis.

Intermediate 12 min read

What You'll Learn

  • Identify the roles of the `ini` and `model` blocks in an nlmixr2 function.
  • Express typical values and interindividual variability for pharmacokinetic parameters.
  • Relate one-compartment differential equations to predicted concentrations.
  • Check the key fields and event conventions in nlmixr2 input data.
  • Diagnose mismatches between model states, dose records, and observation records.
  • Distinguish a model definition and data object from the estimation procedure that uses them.

From Model Specification to Data

An nlmixr2 analysis brings together two objects: a model function that describes the population and individual-level relationships, and an R data frame that supplies doses, observation times, outcomes, and covariates. The function is not just a list of parameter names. Its equations define how a dose produces a predicted concentration, while its statistical terms describe variability around that prediction.

A useful way to check a specification is to follow one record through the whole chain: which subject does it belong to, is it a dose or an observation, which model state receives the dose, and what quantity is compared with the measured dependent variable? This tutorial uses a hypothetical one-compartment model with first-order absorption to illustrate that connection. It focuses on how the model and data are represented, not on choosing or comparing estimation methods.

Definition: An nlmixr2 model function is an R function containing an ini block and a model block. The ini block gives initial values and variability specifications; the model block defines individual parameter relationships, structural equations, and the observation model. The input data are records arranged by subject and time, including event information for dosing and values of the dependent variable for observations.

What the Function Expresses

In the ini block, typical values and variance parameters are given initial values for estimation. For example, tcl can be the log of the typical clearance, and eta.cl can represent a subject-specific deviation on that log scale. In nlmixr2 syntax, a line such as eta.cl ~ 0.1 declares an interindividual random effect and supplies an initial variance value. It does not assert that the final estimated variance will be 0.1.

The model block defines how those quantities combine. Exponentiating a log-scale parameter ensures a positive clearance. Adding a normally distributed random effect on the log scale gives a lognormal distribution of individual clearances. The same pattern can be used for absorption rate and volume. The equations for the amounts in the compartments then define the structural model, and a prediction such as concentration links the structural states to the observation model.

The example below uses a combined additive and proportional residual-error model. In statistical terms, conditional on an individual's model prediction \(f\), the observation has mean \(f\) and variance \(\sigma_a^2+(\sigma_p f)^2\), under the usual independent, mean-zero residual-error assumption. The additive component has the units of the dependent variable; the proportional component is dimensionless. The syntax names the two components, while the values in ini are starting values rather than fixed scientific truths.

Worked Example: Reading a Model Function

Suppose a hypothetical analysis uses clearance in L/h, volume in L, absorption rate in h\(^{-1}\), amount in mg, and concentration in mg/L. A function can be written as follows. The initial values are illustrative, not fitted estimates.

R function:
one.compartment <- function() {
  ini({
    tka <- log(1.2)
    tcl <- log(5)
    tv <- log(20)
    eta.ka ~ 0.1
    eta.cl ~ 0.1
    eta.v ~ 0.1
    add.err <- 0.2
    prop.err <- 0.1
  })
  model({
    ka <- exp(tka + eta.ka)
    cl <- exp(tcl + eta.cl)
    v <- exp(tv + eta.v)
    d/dt(depot) <- -ka * depot
    d/dt(centr) <- ka * depot - (cl/v) * centr
    cp <- centr / v
    cp ~ add(add.err) + prop(prop.err)
  })
}

The typical values are \(ka=\exp(\log(1.2))=1.2\) h\(^{-1}\), \(CL=\exp(\log(5))=5\) L/h, and \(V=\exp(\log(20))=20\) L when the random effects are zero. The individual clearance is \(CL_i=\exp(tcl+\eta_{cl,i})\), with analogous expressions for \(ka_i\) and \(V_i\). The depot loses amount at rate \(ka\) times its amount; the central compartment gains that absorbed amount and loses amount at rate \((CL/V)\) times central amount. Dividing central amount by volume gives the predicted concentration \(cp\).

The code declares a structural model and statistical variability, but the declarations alone do not demonstrate that a data set has compatible dose records, units, or observation values. Those require separate checks.

Structural Equations and Their Interpretation

For this example, let \(A_d(t)\) and \(A_c(t)\) denote the amounts in the depot and central compartments. Assume first-order absorption, first-order elimination from the central compartment, fixed parameters within a subject, and a dose placed in the depot at time zero. For a single oral dose \(D\), bioavailability \(F=1\), and initial amounts \(A_d(0)=D\) and \(A_c(0)=0\), the equations are

$$ \frac{dA_d}{dt}=-ka A_d,\qquad \frac{dA_c}{dt}=ka A_d-\frac{CL}{V}A_c,\qquad C_p=\frac{A_c}{V}. $$

Writing \(k=CL/V\), the depot equation has solution \(A_d(t)=D e^{-ka t}\). Substituting that solution into the central-compartment equation gives a linear differential equation. Multiplying by the integrating factor \(e^{kt}\) yields

$$ \frac{d}{dt}\{e^{kt}A_c(t)\}=kaD e^{(k-ka)t}. $$

Integrating from zero to \(t\), and using \(A_c(0)=0\), gives \(A_c(t)=Dka(e^{-kt}-e^{-ka t})/(ka-k)\) when \(ka\ne k\). Thus the predicted concentration is

$$ C_p(t)=\frac{Dka}{V(ka-k)} \left(e^{-kt}-e^{-ka t}\right),\qquad k=\frac{CL}{V}. $$

This derivation explains why model equations and data event records must agree. A dose entered at the wrong time or in the wrong compartment changes the initial conditions and therefore changes the predicted concentration, even if the parameter values and differential equations are unchanged.

Worked Example: Checking a Structural Prediction

Use the hypothetical values \(D=100\) mg, \(ka=1.2\) h\(^{-1}\), \(CL=5\) L/h, and \(V=20\) L. Assume \(F=1\), a dose into the depot at time zero, and no other doses. Find the model-predicted concentration at 2 hours.

First calculate \(k=CL/V=5/20=0.25\) h\(^{-1}\). Substitution into the derived solution gives

$$ C_p(2)= \frac{100(1.2)}{20(1.2-0.25)} \left(e^{-0.25(2)}-e^{-1.2(2)}\right). $$

The coefficient is \(120/19=6.316\) mg/L. The exponential terms are \(e^{-0.5}=0.6065\) and \(e^{-2.4}=0.09072\), so \(C_p(2)=6.316(0.6065-0.09072)=3.258\) mg/L, approximately. This is a model prediction under the stated assumptions, not a measured concentration or an estimate from data.

Connecting the Model to an R Data Frame

The model function does not contain the observed study records. Those are supplied separately as an R data frame. Names and exact requirements can depend on the data and model setup, but a typical event data set identifies the subject, event time, dependent variable, dose amount, event type, and compartment. Covariates such as weight can be additional columns. Dose records and observation records are distinct: a dose record describes an input to the system, while an observation record supplies a measured outcome to compare with the model prediction.

A NONMEM-style event data frame commonly uses fields such as ID, TIME, DV, AMT, EVID, and CMT. In that convention, an observation has EVID=0, while a dose has EVID=1; the dose amount and target compartment must be coded consistently with the model's state compartments and software event conventions. Observation rows carry the measured dependent variable, while dose rows ordinarily have no measured dependent-variable value. Do not infer compartment numbering from a label alone: check the event mapping expected by the actual model and data setup.

Worked Example: Inspecting Hypothetical Event Records

Consider a hypothetical subject receiving a 100 mg oral dose at time 0, with concentration observations at 1 and 2 hours. Suppose the model-data setup defines compartment 1 as depot and compartment 2 as central for these records. A compact data frame could be specified as:

R data:
dat <- data.frame(
  ID = c(1, 1, 1),
  TIME = c(0, 1, 2),
  DV = c(NA, 2.70, 3.26),
  AMT = c(100, 0, 0),
  EVID = c(1, 0, 0),
  CMT = c(1, 2, 2)
)

There are three records for one subject: one dose and two observations. The dose row has \(AMT=100\) mg, \(EVID=1\), and \(CMT=1\), directing the dose to the depot under the stated mapping. The observation rows have \(EVID=0\), no dose amount, and \(DV=2.70\) and \(3.26\) mg/L. At 2 hours, the observed value 3.26 mg/L happens to match the approximate prediction calculated in the previous example; this is chosen hypothetical data, not evidence of model fit.

Before using such a data frame, verify that the time and concentration units agree with the model parameters, the records are assigned to the intended subject, and each dose and observation is represented by the correct event type and compartment. In a real data set, additional event details may be needed, and a minimal illustration should not be mistaken for a universal data specification.

Worked Example: Interindividual Variability on the Log Scale

In the function above, suppose a hypothetical individual has \(\eta_{cl}=0.2\). Given a typical clearance of 5 L/h, their clearance under the specified model is

$$ CL_i=\exp(\log(5)+0.2)=5\exp(0.2)=5(1.2214)=6.107\ \text{L/h}. $$

The deviation is additive on the log scale but multiplicative on the clearance scale: the individual clearance is about 1.221 times the typical value. If the random effect is assumed normally distributed with mean zero and variance \(\omega_{cl}^2\), then clearance is lognormally distributed. The line eta.cl ~ 0.1 supplies an initial variance for that random effect; it does not mean every subject's deviation is 0.1 or that their clearance is 0.1 L/h above typical. The random effect is associated with a subject's records, not independently redrawn at each observation time.

Assumptions, Checks, and Alternatives

The specification is meaningful only under assumptions that match the scientific question and the data. For the illustrated structural model, these include one kinetically mixed central compartment, first-order absorption and elimination, and the chosen dose route and compartment mapping. The statistical specification additionally assumes that the random effects and residual errors have the distributions and independence structure represented by the model. A data frame must use compatible units, valid subject identifiers, interpretable event coding, and correctly recorded dependent-variable values. The model syntax cannot verify those assumptions by itself.

A practical review can trace the following chain:

1
Read the parameter definitions.
Confirm the transformations produce parameters with the intended units and positive values where required.
2
Trace the structural states.
Check that the dose input, differential equations, derived prediction, and dependent variable refer to compatible compartments and quantities.
3
Audit event records.
Check subject IDs, time ordering, dose amounts, event types, compartment assignments, missing values on dose rows, and observed values on observation rows.
4
Check statistical terms.
Confirm that the random-effect structure and residual-error form are scientifically intended, and that initial values are not mistaken for estimated results.

Common warning signs include doses entering an unintended state, concentration values paired with an amount prediction, time units inconsistent with rate units, duplicate or misordered records, and a dependent-variable column populated on dose events. Another frequent error is to read an initial variance as a standard deviation or as a fixed effect. The remedy is to check the declared statistical meaning of each term and the units of the quantity it describes, not to rely on the variable name alone.

An nlmixr2 function is one way to express a model in R. NONMEM control streams and Monolix project/model components organize model and data information differently, while sharing concepts such as structural parameters, random effects, residual error, and event records. The choice of software does not remove the need to make these concepts explicit. Nor does a model function alone simulate a complete analysis: data validation, estimation, and evaluation are separate tasks. A model may also be scientifically inadequate even when its syntax and data are valid, and software-specific event conventions should be checked rather than assumed to transfer unchanged.

Key takeaway: In nlmixr2, the model function states the structural and statistical relationships, while the R data frame supplies subject-level events and observations. Reproducible interpretation depends on checking that the two agree in quantities, units, states, and event meaning.

Check Your Understanding

Answer each question, then compare your reasoning with the solutions.

  1. In an nlmixr2 model function, what roles do the ini and model blocks play?
  2. For \(CL_i=\exp(\log(5)+\eta_{cl,i})\), what is \(CL_i\) when \(\eta_{cl,i}=0\), and what does a positive random effect do to clearance?
  3. In the hypothetical event convention used above, what distinguishes a dose record from an observation record?
  4. Why is a dose entered into the wrong compartment a model-data error even if its amount and time are correct?
  5. What does an initial value for a random-effect variance represent, and what does it not represent?

Solutions. (1) The ini block supplies starting values and variability specifications; the model block defines individual parameter relationships, structural equations, and the observation model. (2) At zero, \(CL_i=\exp(\log(5))=5\) L/h. A positive deviation multiplies typical clearance by \(\exp(\eta_{cl,i})\), so it increases clearance. (3) A dose record has the dose event code, amount, and target compartment; an observation record has the observation event code and measured dependent-variable value. (4) The compartment determines the system state receiving the input, so changing it changes the model's initial conditions and predicted concentration trajectory. (5) It is a starting value for the variance parameter used in estimation; it is not a subject-specific deviation, a standard deviation, or a final estimate.

Clinical Biostats