How to get “RStan” to work in Rstudio

less than 1 minute read

Published:

I came across two error messages while using the $\bf{rstan}$ package in Rstudio. The error messages read as follows:

  • Error 1: “failed to create lock directory “
  • Error 2: “compileCode(f, code, language = language, verbose = verbose)”

$\textbf{Operating system:}$ Windows, $\textbf{R version:}$ 4.2.3.

Solutions:

  • Error 1 was easy to fix, simply run the following line before installing the package.
options("install.lock"=FALSE)
  • Error 2 was a bit tricky. I tried with several solutions and none of it worked. I then learned from this link that the current version of RStan on CRAN is not compatible with R 4.2.3. The following lines will resolve the error.
remove.packages(c("StanHeaders","rstan"))
install.packages("StanHeaders", repos = c("https://mc-stan.org/r-packages/", getOption("repos")))
install.packages("rstan", repos = c("https://mc-stan.org/r-packages/", getOption("repos")))
library(rstan)

Now you can check by running the example model code from Stan, and you should be able to run the following line without encountering any error messages.

example(stan_model, package = "rstan", run.dontrun = TRUE)