I seem to be sharing a lot of code with coauthors these days. Many of them are novice/intermediate R users and don't realize that they have to install packages they don't already have.
Is there an elegant way to call installed.packages()
, compare that to the ones I am loading and install if missing?
I use the following which will check if package is installed and if dependencies are updated, then loads the package.
You can just use the return value of
require
:I use
library
after the install because it will throw an exception if the install wasn't successful or the package can't be loaded for some other reason. You make this more robust and reuseable:The downside to this method is that you have to pass the package name in quotes, which you don't do for the real
require
.A lot of the answers above (and on duplicates of this question) rely on
installed.packages
which is bad form. From the documentation:So, a better approach is to attempt to load the package using
require
and and install if loading fails (require
will returnFALSE
if it isn't found). I prefer this implementation:which can be used like this:
This way it loads all the packages, then goes back and installs all the missing packages (which if you want, is a handy place to insert a prompt to ask if the user wants to install packages). Instead of calling
install.packages
separately for each package it passes the whole vector of uninstalled packages just once.Here's the same function but with a windows dialog that asks if the user wants to install the missing packages
You can simply use the
setdiff
function to get the packages that aren't installed and then install them. In the sample below, we check if theggplot2
andRcpp
packages are installed before installing them.In one line, the above can be written as:
Yes. If you have your list of packages, compare it to the output from
installed.packages()[,"Package"]
and install the missing packages. Something like this:Otherwise:
If you put your code in a package and make them dependencies, then they will automatically be installed when you install your package.
In my case, I wanted a one liner that I could run from the commandline (actually via a Makefile). Here is an example installing "VGAM" and "feather" if they are not already installed:
From within R it would just be:
There is nothing here beyond the previous solutions except that:
repos
parameter (to avoid any popups asking about the mirror to use)Also note the important
character.only=TRUE
(without it, therequire
would try to load the packagep
).