Compile Stan model in Shiny App?

As I have a windows system, I set myself up on the amazon web service and set up RStudio as is described on http://www.louisaslett.com/RStudio_AMI. But, I can’t get Stan to run at all on there.

Any idea why I can’t compile a Stan model on there? I’m trying to use a compiled model to make a shiny app as I don’t think my compiled model on windows seems to be working for it: https://vianey-leosbarajas.shinyapps.io/BayesSIR/
@charlesm93

Sorry if this is a silly question, but once all of these steps are complete and the app is deployed from a Linux system using the .rds files for the models with the correct compiler flag, will the app work on shinyapps.io from any computer? i.e. will the person using the app need to follow these steps every time, or will the app “just work” by using the compiled .rds files?

I encountered this task recently and just wanted to share some additional details I worked out for generating a shinyapps-compatible binary inside a container.

One can run the rocker r2u image with the Ubuntu version matching the shinyapps infrastructure (22.04 at time of writing) using Podman or Docker. r2u provides pre-compiled binaries of R packages for Ubuntu, so installing rstan inside the container only takes ~15 seconds. These are the steps:

# Start the container, mapping the host path with your .stan file to a folder in the container:
podman run -it -v /host/path/to/stan/:/home/rocker/stan docker.io/rocker/r2u:22.04

# Inside the container, install rstan:
Rscript -e "install.packages('rstan')"

# Update the compiler flags with sed:
sed -i 's/^CXXFLAGS.*/CXXFLAGS = -g -O2 $(LTO)/' /usr/lib/R/etc/Makeconf

# And compile + save your model:
Rscript -e "library(rstan); m = stan_model('/home/rocker/stan/model.stan'); saveRDS(m, '/home/rocker/stan/model.rds')"

And the RDS will now be in the host folder you mapped.

I’m not positive that shinyapps and the corresponding r2u image will always be using the same R version, so you may need to update R in the latter to match the former. But at time of writing they’re both on 4.6.0 and everything works with no tweaks :)