Skip to content

Instantly share code, notes, and snippets.

@otsaloma
Last active September 19, 2023 19:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save otsaloma/f3b8f61a39bf81df0bcc0e5fd80e9ad1 to your computer and use it in GitHub Desktop.
Save otsaloma/f3b8f61a39bf81df0bcc0e5fd80e9ad1 to your computer and use it in GitHub Desktop.
Project specific snapshot dependencies for R
local({
# https://packagemanager.posit.co/client/#/repos/cran/setup
url = "https://packagemanager.posit.co/cran/2023-09-01"
r_version = gsub("\\.\\d+$", "", as.character(getRversion()))
cran_version = rev(unlist(strsplit(url, "/+")))[1]
dir = sprintf("~/.R/library/%s-%s", r_version, cran_version)
message(sprintf("Using %s", url))
message(sprintf("Using %s", dir))
options(repos=url)
if (!dir.exists(dir))
dir.create(dir, recursive=TRUE)
.libPaths(dir)
})
local({
# Source any possible project-specific .init.R first
# as it might set .libPaths for custom dependencies.
# https://gist.github.com/otsaloma/f3b8f61a39bf81df0bcc0e5fd80e9ad1
components = unlist(strsplit(getwd(), "/"))
for (i in length(components):1) {
args = as.list(c(components[1:i], ".init.R"))
path = do.call(file.path, args)
if (file.exists(path)) {
source(path)
break
}
}
})
# Make sure your later .Rprofile doesn't overwrite the above,
# e.g. if you want to set default repos, use the following form.
# options(repos=getOption("repos", "https://cran.rstudio.com/"))
@otsaloma
Copy link
Author

Put the .init.R file in your project root and a piece of code that loads it at the very top of your ~/.Rprofile. Whenever you start R anywhere under the project directory, it should load the snapshot library. Installing packages and everything else should work as normal. If you need custom dependencies, not available in CRAN and the corresponding MRAN snapshot, just add them to the end of .init.R.

@otsaloma
Copy link
Author

Updated to use RStudio's snapshots as Microsoft's MRAN has been unreliable for a while now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment