Installing your usual R packages

R
workflow
shell
Author

Guilherme D. Garcia

Published

April 27, 2026

If you use R, you probably have a small set of packages that you install every time you set up a new machine or update R. This is especially annoying after a major R update, since packages installed under an older version may need to be reinstalled. Of course, you can always install packages manually, but if you know you will need the same packages again and again, you might as well automate the process.

One simple way to do this is to keep a list of your usual packages in your shell configuration file. I use zsh, so this lives in my .zshrc, but the same idea can be adapted to .bashrc if you use bash. The function below installs some packages from CRAN and then installs GitHub packages with pak.

R_PACKAGES=(
  tidyverse
  scales
  stringr
  data.table
  rmarkdown
)

R_GITHUB_PACKAGES=("guilhermegarcia/fonology")

installRpackages() {
  Rscript -e '
    pkgs <- commandArgs(trailingOnly = TRUE)
    install.packages(
      pkgs,
      repos = "https://cloud.r-project.org",
      dependencies = TRUE,
      INSTALL_opts = "--no-lock"
    )
  ' ${=R_PACKAGES}

  if [[ ${#R_GITHUB_PACKAGES[@]} -gt 0 ]]; then
    Rscript -e '
      if (!requireNamespace("pak", quietly = TRUE)) {
        install.packages("pak", repos = "https://cloud.r-project.org")
      }
      pkgs <- commandArgs(trailingOnly = TRUE)
      pak::pak(pkgs)
    ' ${=R_GITHUB_PACKAGES}
  fi
}

The first array, R_PACKAGES, contains packages available on CRAN. You can add or remove package names as needed. The second array, R_GITHUB_PACKAGES, contains packages hosted on GitHub. In the example above, I included my Fonology package, which can be installed with pak::pak("guilhermegarcia/fonology").

Once this is in your .zshrc, restart your terminal or run:

source ~/.zshrc

Then, after installing a new version of R, you can simply run:

installRpackages

That’s it. The point here is to keep your own list somewhere reproducible, so reinstalling your usual R setup becomes a one-command task instead of a long sequence of copy-pasted install.packages() calls.


Copyright © Guilherme Duarte Garcia