Search code examples
rpurrrnlme

Using purrr::possibly() to catch non-positive definite matrix


I am doing a stratified analysis of a mixed effect model using nlme's lme function and thus employing purrr's map function. At times, the number of observations is too small and I get errors from nlme that the matrix is non-positive definite. One of these two errors appears:

  • Error in MEEM(object, conLin, control$niterEM) : Singularity in backsolve at level 0, block 1
  • Error in chol.default((value + t(value))/2) : the leading minor of order 1 is not positive definite

Rather than stopping everything, I rather substitute "NA" using purrr::possibly() when an error occurs.

Here is a trival example to demonstrate this issue.

library(nlme)
library(purrr)
set.seed(423)
 fm2 <- nlme::lme(distance ~ age + Sex, data = Orthodont[sample(108, 3), ], random = ~ 1)
# Error in chol.default((value + t(value))/2) : 
#  the leading minor of order 1 is not positive definite


## Using purrr::possibly()
set.seed(423)
fm2 <- purrr::possibly(
lme(distance ~ age + Sex, data = Orthodont[sample(108, 3), ], random = ~ 1), 
NA
)
# Error in chol.default((value + t(value))/2) : 
#   the leading minor of order 1 is not positive definite

Because I am using possibly() on the nlme function and not the function within lme(), would this explain why possibly() is not working?

Thanks

Session Info

R version 4.2.0 (2022-04-22 ucrt)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19042), RStudio 2022.2.2.485

Locale:
  LC_COLLATE=English_United States.utf8  LC_CTYPE=English_United States.utf8    LC_MONETARY=English_United States.utf8
  LC_NUMERIC=C                           LC_TIME=English_United States.utf8    

Package version:
  lattice_0.20.45 magrittr_2.0.3  nlme_3.1-157    purrr_0.3.4      rlang_1.0.2       

Solution

  • possibly takes a function as input. We can do

    lme2 <- purrr::possibly(lme, otherwise = NA)
    set.seed(423)
     fm2 <- 
     lme2(distance ~ age + Sex, data = Orthodont[sample(108, 3), ], random = ~ 1)
    fm2
    [1] NA