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?
Sure.
You need to compare 'installed packages' with 'desired packages'. That's very close to what I do with CRANberries as I need to compare 'stored known packages' with 'currently known packages' to determine new and/or updated packages.
So do something like
to get all known packages, simular call for currently installed packages and compare that to a given set of target packages.
Quite basic one.
This works with unquoted package names and is fairly elegant (cf. GeoObserver's answer)
"ggplot2" is the package. It checks to see if the package is installed, if it is not it installs it. It then loads the package regardless of which branch it took.
I have implemented the function to install and load required R packages silently. Hope might help. Here is the code: