readRDS fails in R init code chunk

Background: I have a project workflow which involves writing R code chunks in a quarto file in RStudio, optimizing them, (especially the graphics ones), and adding new chunks and discourse until ready for the final production rendering run. One big caveat: when I use cmdstanr for complicated models, after getting each model to have good predictive checks and convergence, I use the save_object method to save the entire model to disc, for easy reloading for the next iteration of writing the document.

However, this reloading step then fails when initializing my next work session.


I have not been able to create a simple reproducible example, as I cannot recreate the problem. But I will walk through the details in the affected project.

After getting the "final" CmdStanMCMC model object, I run the code

<ModelName>.MCMC[['save_object']](file = "models/<ModelName>.rds")

and then set the eval flag to false for these code chunks.

In the first, or initialization/setup, code chunk, I have

# Make new position on search path for more permanent objects,
# keeping .GlobalEnv uncluttered during document writing

.nm <- '<ProjName>'  
if( ! (.nm %in% search()) ) attach(what = NULL, pos = 2, name = .nm)
assign(".nm", value = .nm, pos = .nm)
rm(.nm) 

near the beginning of the chunk.

Later in this chunk, I have

local({

       <ModelName>.MCMC <- readRDS("models/<ModelName>.rds")

      },  envir = as.environment(.nm)
     )

Here is the problem. When starting up a new work session, running this init chunk fails with the message

Warning in gzfile(file, "rb") :
  cannot open compressed file 'models/<ModelName>.rds', probable reason 'No such file or directory'
Error in gzfile(file, "rb") : cannot open the connection

That is the issue.


I tried writing the readRDS command outside the local statement, to put it in the global environment. Same issue.

I tried running the rest of the initialization, after commenting out the reloading statement, then running the command in the R console. Same issue.

Here's where it gets really weird. The following statement always failed when running in the init chunk, but sometimes works properly in the console.

<ModelName>.MCMC <- readRDS(paste("models", dir("models")[<n>], sep = "/") )     # 'n' the appropriate integer

It shouldn't be an .rds compatibility issue, as I'm running version 4.6.0, and the files were generated with 4.5.0.

I thought it might be some funny character encoding issue in my .qmd file. But when I got that command to work, I tried

"models/<ModelName>.rds" == paste("models", dir("models")[<n>], sep = "/")    # 'n' the appropriate integer

copied from the relevant code lines, and got TRUE.

I also tried quitting RStudio, deleting the .Rproj file and recreating the project from scratch there. The problem persists.

I have not seen this issue in three other projects using the same reloading initialization.

Any help or guidance would be appreciated. Thanks!


RStudio info:

RStudio 2026.04.0+526 "Globemaster Allium" Release (57f8932a2d8c5a4a8c0d30ad918ec77f9f2dacaa, 2026-04-18) for macOS
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) RStudio/2026.04.0+526 Chrome/142.0.7444.265 Electron/39.8.7 Safari/537.36, Quarto 1.9.37 (/Applications/quarto/bin/quarto)

R info:

sessionInfo()  # namespace packages coming from .RProfile code options setting etc.
R version 4.6.0 (2026-04-24)
Platform: aarch64-apple-darwin23
Running under: macOS Tahoe 26.4.1

Matrix products: default
BLAS:   /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib 
LAPACK: /Library/Frameworks/R.framework/Versions/4.6/Resources/lib/libRlapack.dylib;  LAPACK version 3.12.1

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

time zone: America/New_York
tzcode source: internal

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

loaded via a namespace (and not attached):
 [1] gtable_0.3.6          jsonlite_2.0.0        compiler_4.6.0        dplyr_1.2.1           tidyselect_1.2.1     
 [6] Rcpp_1.1.1-1.1        parallel_4.6.0        gridExtra_2.3         splines_4.6.0         scales_1.4.0         
[11] ggplot2_4.0.3         R6_2.6.1              generics_0.1.4        curl_7.1.0            knitr_1.51           
[16] tibble_3.3.1          pillar_1.11.1         RColorBrewer_1.1-3    rlang_1.2.0           V8_8.2.0             
[21] inline_0.3.21         Rttf2pt1_1.3.14       xfun_0.57             rstan_2.32.7          S7_0.2.2             
[26] otel_0.2.0            RcppParallel_5.1.11-2 cli_3.6.6             magrittr_2.0.5        grid_4.6.0           
[31] rstudioapi_0.18.0     lifecycle_1.0.5       StanHeaders_2.32.10   vctrs_0.7.3           extrafont_0.20       
[36] evaluate_1.0.5        glue_1.8.1            farver_2.1.2          QuickJSR_1.10.0       extrafontdb_1.1      
[41] codetools_0.2-20      stats4_4.6.0          pkgbuild_1.4.8        matrixStats_1.5.0     tools_4.6.0          
[46] loo_2.9.0             pkgconfig_2.0.3 
1 Like