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?
Dason K. and I have the pacman package that can do this nicely. The function
p_load
in the package does this. The first line is just to ensure that pacman is installed.Regarding your main objective " to install libraries they don't already have. " and regardless of using " instllaed.packages() ". The following function mask the original function of require. It tries to load and check the named package "x" , if it's not installed, install it directly including dependencies; and lastly load it normaly. you rename the function name from 'require' to 'library' to maintain integrity . The only limitation is packages names should be quoted.
So you can load and installed package the old fashion way of R. require ("ggplot2") require ("Rcpp")
Using lapply family and anonymous function approach you may:
||
lazy evaluation).Print each package final load status (
TRUE
/FALSE
).