automatically create personal library in R

burger picture burger · Oct 5, 2016 · Viewed 9.4k times · Source

When you try to install a package in R and you don't have access rights to the default library path, R will ask you:

Would you like to use a personal library instead?

Would you like to create a personal library '~/path' to install packages into?

However, if you are running an Rscript, those messages will not show up and installation will fail. I could predefine a specific path and instruct install.packages to use it, but I don't want to create an additional library path that would be specific to this Rscript. I just want to use the default personal library. Is there a way to force creation of a personal library without requiring interaction?

Answer

burger picture burger · Apr 7, 2017

You can use Sys.getenv("R_LIBS_USER") to get the local library search location.

This is what I ended up doing, which seems to be working (the hardest part was testing the solution, since the problem only occurs the first time you try to install a package):

# create local user library path (not present by default)
dir.create(path = Sys.getenv("R_LIBS_USER"), showWarnings = FALSE, recursive = TRUE)
# install to local user library path
install.packages(p, lib = Sys.getenv("R_LIBS_USER"), repos = "https://cran.rstudio.com/")
# Bioconductor version (works for both Bioconductor and CRAN packages)
BiocManager::install(p, update = FALSE, lib = Sys.getenv("R_LIBS_USER"))

As @hrbrmstr pointed out in the comments, it may not be a good idea to force-install packages, so use at your own risk.