Elegant way to check for missing packages and install them?
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?
Yes. If you have your list of packages, compare it to the output from installed.packages()[,"Package"]
and install the missing packages. Something like this:
list.of.packages <- c("ggplot2", "Rcpp")
new.packages <- list.of.packages[!(list.of.packages %in% installed.packages()[,"Package"])]
if(length(new.packages)) install.packages(new.packages)
Otherwise:
If you put your code in a package and make them dependencies, then they will automatically be installed when you install your package.
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.
if (!require("pacman")) install.packages("pacman")
pacman::p_load(package1, package2, package_n)
You can just use the return value of require
:
if(!require(somepackage)){
install.packages("somepackage")
library(somepackage)
}
I use library
after the install because it will throw an exception if the install wasn't successful or the package can't be loaded for some other reason. You make this more robust and reuseable:
dynamic_require <- function(package){
if(eval(parse(text=paste("require(",package,")")))) return True
install.packages(package)
return eval(parse(text=paste("require(",package,")")))
}
The downside to this method is that you have to pass the package name in quotes, which you don't do for the real require
.
上一篇: 我可以在不重建包的情况下编辑NAMESPACE文件吗?
下一篇: 优雅的方式来检查丢失的包并安装它们?