Install all R packages used in the code

Published on ; updated on

Here is a one-liner I use to install all R dependencies of a script. It is especially useful if you need to run your code on a server or cluster.

perl -lne '/library\((.*)\)/ && print $1' *.R *.Rmd | xargs Rscript -e 'install.packages(commandArgs(T), repos = "https://cran.rstudio.com")'

An alternative is to use p_load from the pacman package in your R scripts instead of library.

See also the discussion in Elegant way to check for missing packages and install them?.