Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I make install.packages return an error if an R package cannot be installed?

Tags:

r

install.packages() returns a warning if a package cannot be installed (for instance, if it is unavailable); for example:

install.packages("notapackage")

(EDIT: I'd like to throw an error regardless of the reason the package cannot be installed, not just this example case of a missing package).

I am running the install.packages command in a script, and I would like it to trigger a proper error and exit execution. I don't see an obvious option inside install.packages for handling this behavior. Any suggestions?

like image 381
cboettig Avatar asked Oct 07 '14 20:10

cboettig


People also ask

Why is R not letting me install packages?

Changing the configuration in R Studio to solve install packages issue. Go To Tools -> Global option -> Packages. Then uncheck the option “Use secure download method for HTTP”. For other RStudio issues refer to official Troubleshooting Guide here.

How check R package is installed or not?

packages() Calling installed. packages() returns a detailed data frame about installed packages, not only containing names, but also licences, versions, dependencies and more.


2 Answers

Having just solved this for myself, I noted that install.packages() results in calling library(thepackage) to see it its usable.

I made a R script that installs the given packages, uses library on each to see if its loadable, and if not calls quit with a non-0 status.

I call it install_packages_or_die.R

#!/usr/bin/env Rscript

packages = commandArgs(trailingOnly=TRUE)

for (l in packages) {

    install.packages(l, dependencies=TRUE, repos='https://cran.rstudio.com/');

    if ( ! library(l, character.only=TRUE, logical.return=TRUE) ) {
        quit(status=1, save='no')
    }
}

Use it like this in your Dockerfile. I'm grouping them in useful chunks to try and make reasonable use of Docker build cache.

ADD install_packages_or_die.R /

RUN Rscript --no-save install_packages_or_die.R profvis devtools memoise

RUN Rscript --no-save install_packages_or_die.R memoise nosuchpackage

Disclaimer: I do not consider myself an R programmer at all currently, so there may very well be better ways of doing this.

like image 119
Cameron Kerr Avatar answered Sep 28 '22 05:09

Cameron Kerr


The R function WithCallingHandlers() lets us handle any warnings with an explicitly defined function. For instance, we can tell the R to stop if it receives any warnings (and return the warning message as an error message).

withCallingHandlers(install.packages("notapackage"),
                    warning = function(w) stop(w))

I am guessing that this is not ideal, since presumably a package could install successfully but still throw a warning; but haven't encountered that case. As Dirk suggests, testing require for the package is probably more robust.

like image 31
cboettig Avatar answered Sep 28 '22 03:09

cboettig