Enjoy R: install packages “on the fly”

It is annoying when you load a package and you find out you don’t have it installed. So you need to install it first, and finally load it.
As I am used to installing LaTeX packages on the fly, I thought of a simple script to do the same in R. The following is a banal code, which can be easily customized by the user in case there is a need to specify some more arguments concerning maybe install.packages() and/or library().

usepackages = Vectorize(function(x) {
  
  stopifnot(is.character(x))
  
  if(!is.element(x, rownames(installed.packages()))) install.packages(x)
  
  library(x, character.only = T, logical.return = T, quietly = T)
  
})

Let’s try to load three packages, one of which (SafeBayes) has to be installed on the fly.

usepackages

The named logical vector at the very end of the output is the result of the vectorization of the argument logical.return of the function library() which returns TRUE if the package has been successfully loaded, and FALSE otherwise.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: