automatically create personal library in R

12,332

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.

Share:
12,332
burger
Author by

burger

Updated on July 06, 2022

Comments

  • burger
    burger almost 2 years

    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?

  • llrs
    llrs over 3 years
    Note that biocLite should no longer be used to install packages from Bioconductor. Use BiocManager::install()
  • bers
    bers almost 2 years
    Important to note: While you can set R_LIBS_USER in your environment, and R will respect that, Sys.getenv("R_LIBS_USER") will return something sensible even if R_LIBS_USER is not set in your environment.