0

Is there a "standard" way to load a package, and install it if it isn't installed yet? Something like

if (!is.installed(package))
    install(package)
library(package)

(pseudocode!), encapsulated in a neat function?

I'm usually having a hard time after wiping my private site library, which I do every now and then. If my scripts all used this "install-on-demand" facility, this would just happen automatically.

krlmlr
  • 25,056
  • 14
  • 120
  • 217
  • I use what you suggest with `is.installed <- function(mypkg) is.element(mypkg, installed.packages()[,1])`. Of course, I set `dependencies=TRUE`. – Roland Nov 07 '13 at 14:23
  • @Roland: So, no package that provides this functionality? – krlmlr Nov 07 '13 at 14:25
  • I do this: http://stackoverflow.com/questions/19596359/install-package-library-if-not-installed/19598076#19598076 – Alex Vorobiev Nov 07 '13 at 14:54

2 Answers2

2

Dason K. and I have a package in the works on GitHub that needs some testing and a bit of cleaning and eventually will be pushed to CRAN. The function p_load in the package does this.

library(devtools)
install_github("trinker/pacman")
Tyler Rinker
  • 108,132
  • 65
  • 322
  • 519
  • Thanks! Why don't you rather answer the linked question, now this is an official dupe? Also, how does `pacman` compare with [`packrat`](https://github.com/rstudio/packrat) and [`rbundler`](https://github.com/opower/rbundler)? – krlmlr Nov 07 '13 at 20:55
  • *bump* Why don't you re-post it here, where it might get more attention: http://stackoverflow.com/questions/4090169/elegant-way-to-check-for-missing-packages-and-install-them?lq=1 – krlmlr Nov 09 '13 at 07:17
  • @krlmlr **pacman** does very different things than **packrat**. The former works to improve workflow through more consistently named and compact acting functions while the later seems to be more focused on preserving a particular environment, both useful for different purposes. – Tyler Rinker Feb 15 '15 at 02:12
0

I see that other answers have been given but my preference would be:

 if ( !require('pkg') ) { install.packages('pkg', dependencies=TRUE);
                        require('pkg') }

If you want to suppress the warning, then add quietly=TRUE to the first require call. I suppose you could bundle this into a function, called, what? insist?

 insist <- function(pkg){
          if ( !require(pkg, character.only=TRUE) ) { 
                    install.packages(as.character(pkg), dependencies=TRUE)
          require(pkg, character.only=TRUE) }
                         }

(My major stumbling block: The first argument to require didn't seem to get evaluated unless character.only=TRUE. Took me several reads of the ?require page to get this idea. Just slow, I guess.)

IRTFM
  • 258,963
  • 21
  • 364
  • 487