R searches an ordered set of library directories whenever it installs or loads an add-on package. A personal library puts one account's packages first without granting write access to system-wide R directories.
The R_LIBS_USER environment variable supplies that directory during startup, and ~/.Renviron stores environment variables for one user. R retains only library directories that exist when the session starts, so create the directory before starting the session that checks the change.
A fixed ~/R/library path keeps the same location across R minor releases. Packages containing compiled code may still require reinstallation after an R upgrade, while site and system libraries remain later in .libPaths() for administrator-managed packages.
Steps to set a user package library in R:
- Create the personal R package directory.
$ mkdir -p ~/R/library
- Open the per-user environment file in nano.
$ nano ~/.Renviron
- Add the R_LIBS_USER setting on a new line.
R_LIBS_USER="${HOME}/R/library"The ${HOME} expansion avoids embedding an account name in the configuration.
- Save ~/.Renviron in nano.
- Exit nano to return to the shell.
- Start a fresh R session without restoring a saved workspace.
$ R --quiet --no-save >
R reads ~/.Renviron during startup. An existing session does not rebuild its library path after the file changes.
- Confirm the personal directory appears first in the active library search path.
> .libPaths() [1] "/home/analyst/R/library" "/usr/local/lib/R/site-library" [3] "/usr/lib/R/site-library" "/usr/lib/R/library"
The home directory differs by account and operating system. The important state is that the writable personal directory appears before the site and system libraries.
- Install the crayon test package into the active personal library.
> install.packages("crayon", repos = "https://cloud.r-project.org") Installing package into '/home/analyst/R/library' (as 'lib' is unspecified) trying URL 'https://cloud.r-project.org/src/contrib/crayon_1.5.3.tar.gz' ##### snipped ##### * DONE (crayon) - Resolve the installed crayon namespace path from the active library search path.
> getNamespaceInfo(loadNamespace("crayon"), "path") [1] "/home/analyst/R/library/crayon"
Mohd Shakir Zakaria is a cloud architect with deep roots in software development and open-source advocacy. Certified in AWS, Red Hat, VMware, ITIL, and Linux, he specializes in designing and managing robust cloud and on-premises infrastructures.