nlmixr

nlmixr

The broom and broom.mixed packages

broom and broom.mixed are packages that attempt to put standard model outputs into data frames. nlmixr supports the tidy and glance methods but does not support augment at this time.

Using a model with a covariance term, the Phenobarbital model, we can explore the different types of output that is used in the tidy functions.

To explore this, first we run the model:

library(nlmixr)
## To allow nlmixr to reload runs without large run times
## To run the actual models on your system, take the save options off.
options(nlmixr.save=TRUE,
        nlmixr.save.dir=system.file(package="nlmixr"));

pheno <- function() {
    # Pheno with covariance
  ini({
    tcl <- log(0.008) # typical value of clearance
    tv <-  log(0.6)   # typical value of volume
    ## var(eta.cl)
    eta.cl + eta.v ~ c(1, 
                       0.01, 1) ## cov(eta.cl, eta.v), var(eta.v)
                      # interindividual variability on clearance and volume
    add.err <- 0.1    # residual variability
  })
  model({
    cl <- exp(tcl + eta.cl) # individual value of clearance
    v <- exp(tv + eta.v)    # individual value of volume
    ke <- cl / v            # elimination rate constant
    d/dt(A1) = - ke * A1    # model differential equation
    cp = A1 / v             # concentration in plasma
    cp ~ add(add.err)       # define error model
  })
}

## We will run it two ways to allow comparisons
fit.s <- nlmixr(pheno, pheno_sd, "saem", control=list(logLik=TRUE), table=list(cwres=TRUE))
#> Loading model already run (/home/matt/R/x86_64-pc-linux-gnu-library/3.5/nlmixr/nlmixr-pheno-pheno_sd-saem-8fe800ec2560aaafea0009fc5b269afe.rds)
fit.f <- nlmixr(pheno, pheno_sd, "focei")
#> Loading model already run (/home/matt/R/x86_64-pc-linux-gnu-library/3.5/nlmixr/nlmixr-pheno-pheno_sd-focei-a21c20746071ba2bc8e5739d3f0f8928.rds)

Glancing at the goodness of fit metrics

Often in fitting data, you would want to glance at the fit to see how well it fits. In broom, glance will give a summary of the fit metrics of goodness of fit:

glance(fit.s)
OBJF AIC BIC logLik conditionNumber
689 986 1e+03 -487 7.46

Note in nlmixr it is possible to have more than one fit metric (based on different quadratures, FOCEi approximation etc). However, the glance only returns the fit metrics that are current.

If you wish you can set the objective function to the focei objective function (which was already calculated with CWRES).

setOfv(fit.s,"FOCEi")

Now the glance gives the FOCEi values.

glance(fit.s)
OBJF AIC BIC logLik conditionNumber
689 986 1e+03 -487 7.46

Of course you can always change the type of objective function that nlmixr uses:

setOfv(fit.s,"gauss3_1.6") # Setting objective function to gauss3_1.6

By setting it back to the SAEM default objective function of gauss3_1.6, the glance(fit.s) has the same values again:

glance(fit.s)
OBJF AIC BIC logLik conditionNumber
722 1.02e+03 1.04e+03 -503 7.46

For convenience, you can do this while you glance at the objects:

glance(fit.s, type="FOCEi")
OBJF AIC BIC logLik conditionNumber
689 986 1e+03 -487 7.46

Tidying the model parameters

Tidying of overall fit parameters

You can also tidy the model estimates into a data frame with broom for processing. This can be useful when integrating into 3rd parting modeling packages. With a consistent parameter format, tasks for multiple types of models can be automated and applied.

The default function for this is tidy, which when applied to the fit object provides the overall parameter information in a tidy dataset:

tidy(fit.s)
effect group term estimate std.error statistic p.value
fixed tcl -5     0.075  -66.7  1       
fixed tv 0.347 0.0536 6.48 6.37e-10
ran_pars ID sd__eta.cl 0.496                  
ran_pars ID sd__eta.v 0.392                  
ran_pars ID cor__eta.v.eta.cl 0.986                  
ran_pars Residual(add) add.err 2.84                   

Note by default these are the parameters that are actually estimated in nlmixr, not the back-transformed values in the table from the printout. Of course, with mu-referenced models, you may want to exponentiate some of the terms. The broom package allows you to apply exponentiation on all the parameters, that is:

## Transformation applied on every parameter
tidy(fit.s, exponentiate=TRUE) 
effect group term estimate std.error statistic p.value
fixed tcl 0.00674 0.000505 13.3 1.7e-27 
fixed tv 1.42    0.0759   18.7 4.11e-41
ran_pars ID sd__eta.cl 0.496                     
ran_pars ID sd__eta.v 0.392                     
ran_pars ID cor__eta.v.eta.cl 0.986                     
ran_pars Residual(add) add.err 2.84                      

Note:, in accordance with the rest of the broom package, when the parameters with the exponentiated, the standard errors are transformed to an approximate standard error by the formula: \(\textrm{se}(\exp(x)) \approx \exp(\textrm{model estimate}_x)\times \textrm{se}_x\). This can be confusing because the confidence intervals (described later) are using the actual standard error and back-transforming to the exponentiated scale. This is the reason why the default for nlmixr’s broom interface is exponentiate=FALSE, that is:

tidy(fit.s, exponentiate=FALSE) ## No transformation applied
effect group term estimate std.error statistic p.value
fixed tcl -5     0.075  -66.7  1       
fixed tv 0.347 0.0536 6.48 6.37e-10
ran_pars ID sd__eta.cl 0.496                  
ran_pars ID sd__eta.v 0.392                  
ran_pars ID cor__eta.v.eta.cl 0.986                  
ran_pars Residual(add) add.err 2.84                   

If you want, you can also use the parsed back-transformation that is used in nlmixr tables (ie fit$parFixedDf). Please note that this uses the approximate back-transformation for standard errors on the log-scaled back-transformed values.

This is done by:

## Transformation applied to log-scaled population parameters
tidy(fit.s, exponentiate=NA) 
effect group term estimate std.error statistic p.value
fixed tcl 0.00674 0.000505 13.3 1.7e-27 
fixed tv 1.42    0.0759   18.7 4.11e-41
ran_pars ID sd__eta.cl 0.496                     
ran_pars ID sd__eta.v 0.392                     
ran_pars ID cor__eta.v.eta.cl 0.986                     
ran_pars Residual(add) add.err 2.84                      

Also note, at the time of this writing the default separator between variables is ., which doesn’t work well with this model giving cor__eta.v.eta.cl. You can easily change this by:

options(broom.mixed.sep2="..")
tidy(fit.s)
effect group term estimate std.error statistic p.value
fixed tcl -5     0.075  -66.7  1       
fixed tv 0.347 0.0536 6.48 6.37e-10
ran_pars ID sd__eta.cl 0.496                  
ran_pars ID sd__eta.v 0.392                  
ran_pars ID cor__eta.v..eta.cl 0.986                  
ran_pars Residual(add) add.err 2.84                   

This gives an easier way to parse value: cor__eta.v..eta.cl

Adding a confidence interval to the parameters

The default R method confint works with nlmixr fit objects:

confint(fit.s)
model.est estimate 2.5 % 97.5 %
-5     0.00674 -5.15  -4.85 
0.347 1.42    0.242 0.452
2.84  2.84             

This transforms the variables as described above. You can still use the exponentiate parameter to control the display of the confidence interval:

confint(fit.s, exponentiate=FALSE)
model.est estimate 2.5 % 97.5 %
-5     0.00674 -5.15  -4.85 
0.347 1.42    0.242 0.452
2.84  2.84             

However, broom has also implemented it own way to make these data a tidy dataset. The easiest way to get these values in a nlmixr dataset is to use:

tidy(fit.s, conf.level=0.9)

effect group term estimate std.error statistic p.value conf.low conf.high
fixed tcl -5     0.075  -66.7  1        -5.12  -4.88 
fixed tv 0.347 0.0536 6.48 6.37e-10 0.259 0.435
ran_pars ID sd__eta.cl 0.496                            
ran_pars ID sd__eta.v 0.392                            
ran_pars ID cor__eta.v..eta.cl 0.986                            
ran_pars Residual(add) add.err 2.84                             
The confidence interval is on the scale specified by exponentiate, by default the estimated scale.

If you want to have the confidence on the adaptive back-transformed scale, you would simply use the following:

tidy(fit.s, conf.level=0.9, exponentiate=NA)
effect group term estimate std.error statistic p.value conf.low conf.high
fixed tcl 0.00674 0.000505 13.3 1.7e-27  0.00595 0.00762
fixed tv 1.42    0.0759   18.7 4.11e-41 1.3     1.55   
ran_pars ID sd__eta.cl 0.496                                   
ran_pars ID sd__eta.v 0.392                                   
ran_pars ID cor__eta.v..eta.cl 0.986                                   
ran_pars Residual(add) add.err 2.84                                    

Extracting other model information with tidy

The type of information that is extracted can be controlled by the effects argument.

Extracting only fixed effect parameters

The fixed effect parameters can be extracted by effects="fixed"

tidy(fit.s, effects="fixed")
effect term estimate std.error statistic p.value
fixed tcl -5     0.075  -66.7  1       
fixed tv 0.347 0.0536 6.48 6.37e-10

Extracting only random parameters

The random standard deviations can be extracted by effects="ran_pars":

tidy(fit.s, effects="ran_pars")
effect group term estimate
ran_pars ID sd__eta.cl 0.496
ran_pars ID sd__eta.v 0.392
ran_pars ID cor__eta.v..eta.cl 0.986
ran_pars Residual(add) add.err 2.84 

Extracting random values (also called ETAs)

The random values, or in NONMEM the ETAs, can be extracted by effects="ran_vals" or effects="random"

head(tidy(fit.s, effects="ran_vals"))
effect group level term estimate
ran_vals ID 1 eta.cl -0.0731
ran_vals ID 2 eta.cl -0.215 
ran_vals ID 3 eta.cl 0.258 
ran_vals ID 4 eta.cl -0.54  
ran_vals ID 5 eta.cl 0.32  
ran_vals ID 6 eta.cl -0.122 

This duplicate method of running effects is because the broom package supports effects="random" while the broom.mixed package supports effects="ran_vals".

Extracting random coefficients

Random coefficients are the population fixed effect parameter + the random effect parameter, possibly transformed to the correct scale.

In this case we can extract this information from a nlmixr fit object by:

head(tidy(fit.s, effects="ran_coef"))

effect group level term estimate
ran_coef ID 1 tcl -5.07
ran_coef ID 2 tcl -5.21
ran_coef ID 3 tcl -4.74
ran_coef ID 4 tcl -5.54
ran_coef ID 5 tcl -4.68
ran_coef ID 6 tcl -5.12
This can also be changed by the exponentiate argument:
head(tidy(fit.s, effects="ran_coef", exponentiate=NA))
effect group level term estimate
ran_coef ID 1 tcl 0.00626
ran_coef ID 2 tcl 0.00543
ran_coef ID 3 tcl 0.00872
ran_coef ID 4 tcl 0.00392
ran_coef ID 5 tcl 0.00928
ran_coef ID 6 tcl 0.00596
head(tidy(fit.s, effects="ran_coef", exponentiate=TRUE))
effect group level term estimate
ran_coef ID 1 tcl 0.00626
ran_coef ID 2 tcl 0.00543
ran_coef ID 3 tcl 0.00872
ran_coef ID 4 tcl 0.00392
ran_coef ID 5 tcl 0.00928
ran_coef ID 6 tcl 0.00596

Example of using a tidy model estimates for other packages

Dotwhisker

As explained above, this standard format makes it easier for tidyverse packages to interact with model information. An example of this is piping the tidy information to dplyr to filter the effects and then to the dotwhisker package to plot the model parameter confidence intervals.

options(broom.mixed.sep2=": ", broom.mixed.sep2=", ")
library(ggplot2)
library(dotwhisker)
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
fit.s %>%
    tidy(exponentiate=NA) %>%
    filter(effect=="fixed") %>%
    dwplot()

You may also compare models easily by using the dotwhisker package

dwplot(list("SAEM"=fit.s, "FOCEi"=fit.f), exponentiate=NA)

Huxtable

This allows easy creation of report ready tables in many formats including word.

Huxtable relies on the broom implementation

library(huxtable)
#> 
#> Attaching package: 'huxtable'
#> The following object is masked from 'package:dplyr':
#> 
#>     add_rownames
#> The following object is masked from 'package:ggplot2':
#> 
#>     theme_grey
tbl <- huxreg('Phenobarbitol'=fit.s)
#> Warning in checkMatrixPackageVersion(): Package version inconsistency detected.
#> TMB was built with Matrix version 1.2.15
#> Current Matrix version is 1.2.17
#> Please re-install 'TMB' from source using install.packages('TMB', type = 'source') or ask CRAN for a binary version of 'TMB' matching CRAN's 'Matrix' package
#> Warning in huxreg(Phenobarbitol = fit.s): Unrecognized statistics: r.squared
#> Try setting `statistics` explicitly in the call to `huxreg()`

tbl
Phenobarbitol
tcl -5.000    
(0.075)   
tv 0.347 ***
(0.054)   
sd__eta.cl 0.496    
sd__eta.v 0.392    
cor__eta.v, eta.cl 0.986    
add.err 2.840    
N 155        
logLik -486.790    
AIC 985.579    
*** p < 0.001; ** p < 0.01; * p < 0.05.

You may notice warnings and (NA) in the table. nlmixr allows you to convert the tables to huxtables without these distracting elements by using huxtable’s generic as_hux or as_huxtable:

as_hux('Phenobarbitol'=fit.s)
#> Warning in (function (..., error_format = "({std.error})", error_style = c("stderr", : Unrecognized format columns: ifelse(!sapply(seq_along(std.error), function(x){any(is.na(c(std.error[x])))
#> These will be replaced with an empty string.
#> Try changing `error_format` in the call to `huxreg()`
Phenobarbitol
tcl -5.000    
tv 0.347 ***
sd: eta.cl 0.496    
sd: eta.v 0.392    
cor: eta.v, eta.cl 0.986    
add.err 2.840    
N 155        
Objective Function 688.709    
logLik -486.790    
AIC 985.579    
*** p < 0.001; ** p < 0.01; * p < 0.05.

Like dwplot, you can also use huxtable to compare runs:

as_hux('SAEM'=fit.s, 'FOCEi'=fit.f)
#> Warning in (function (..., error_format = "({std.error})", error_style = c("stderr", : Unrecognized format columns: ifelse(!sapply(seq_along(std.error), function(x){any(is.na(c(std.error[x])))
#> These will be replaced with an empty string.
#> Try changing `error_format` in the call to `huxreg()`
SAEM FOCEi
tcl -5.000     -5.008    
tv 0.347 *** 0.328 ***
sd: eta.cl 0.496     0.500    
sd: eta.v 0.392     0.394    
cor: eta.v, eta.cl 0.986     0.980    
add.err 2.840     2.838    
N 155         155        
Objective Function 688.709     688.697    
logLik -486.790     -486.784    
AIC 985.579     985.568    
*** p < 0.001; ** p < 0.01; * p < 0.05.

A word-based table can also be easily created with the tool:

library(officer)
library(flextable)
#> 
#> Attaching package: 'flextable'
#> The following objects are masked from 'package:huxtable':
#> 
#>     align, as_flextable, bold, font, height, italic, set_caption,
#>     valign, width

ft  <- huxtable::as_flextable(tbl);
    
read_docx() %>%
    flextable::body_add_flextable(ft)  %>%
    print(target="pheno.docx")
#> [1] "/home/matt/src/nlmixr/vignettes/pheno.docx"

Which produces the following word document.

Happy tidying!