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?
This is the purpose of the rbundler package: to provide a way to control the packages that are installed for a specific project. Right now the package works with the devtools functionality to install packages to your project's directory. The functionality is similar to Ruby's bundler.
If your project is a package (recommended) then all you have to do is load rbundler and bundle the packages. The
bundle
function will look at your package'sDESCRIPTION
file to determine which packages to bundle.Now the packages will be installed in the .Rbundle directory.
If your project isn't a package, then you can fake it by creating a
DESCRIPTION
file in your project's root directory with a Depends field that lists the packages that you want installed (with optional version information):Here's the github repo for the project if you're interested in contributing: rbundler.
I use following function to install package if
require("<package>")
exits with package not found error. It will query both - CRAN and Bioconductor repositories for missing package.Adapted from the original work by Joshua Wiley, http://r.789695.n4.nabble.com/Install-package-automatically-if-not-there-td2267532.html
Example:
PS:
update.packages(ask = FALSE)
&biocLite(character(), ask=FALSE)
will update all installed packages on the system. This can take a long time and consider it as a full R upgrade which may not be warranted all the time!Thought I'd contribute the one I use:
Here's my code for it:
This solution will take a character vector of package names and attempt to load them, or install them if loading fails. It relies on the return behaviour of
require
to do this because...Therefore we can simply see if we were able to load the required package and if not, install it with dependencies. So given a character vector of packages you wish to load...
The following simple function works like a charm:
(not mine, found this on the web some time back and had been using it since then. not sure of the original source)