This question already has an answer here:
这个问题已经有了答案:
- Elegant way to check for missing packages and install them? 25 answers
- 用优雅的方式检查丢失的包并安装它们?25的答案
I have an R script that is shared with several users on different computers. One of its lines contains the install.packages("xtable")
command.
我有一个R脚本,在不同的计算机上与几个用户共享。它的其中一行包含install.packages(“xtable”)命令。
The problem is that every time someone runs the script, R spends a great deal of time apparently reinstalling the package (it actually does take some time, since the real case has vector of several packages).
问题是,每当有人运行这个脚本时,R花费了大量的时间来重新安装这个包(实际上确实需要一些时间,因为实际的例子中有几个包的向量)。
How can I make first check if the packages are installed and then only run install.packages()
for the ones that are not?
我如何首先检查包是否已经安装好,然后只运行安装.package()对于那些没有安装的包?
16 个解决方案
#1
116
try: require("xtable")
or "xtable" %in% rownames(installed.packages())
尝试:需要(“xtable”)或“xtable”% rownames(installed.packages())
#2
39
This is a function I often used to check for a package, install it otherwise and load again:
这是一个我经常用来检查包的函数,安装它,然后重新加载:
pkgTest <- function(x)
{
if (!require(x,character.only = TRUE))
{
install.packages(x,dep=TRUE)
if(!require(x,character.only = TRUE)) stop("Package not found")
}
}
Works like pkgTest("xtable")
. It only works if the mirror is set though, but you could enter that in the require
calls.
就像pkgTest(“xtable”)。它只在镜像设置时有效,但是您可以在需要调用的时候输入它。
#3
36
If you want to do it as simply as possible:
如果你想简单地做到这一点:
packages <- c("ggplot2", "dplyr", "Hmisc", "lme4", "arm", "lattice", "lavaan")
if (length(setdiff(packages, rownames(installed.packages()))) > 0) {
install.packages(setdiff(packages, rownames(installed.packages())))
}
Replace the packages listed on the first line by those needed to run your code, and voilà!
将第一行中列出的包替换为运行代码所需的包,这样就可以了!
#4
11
There's also the CRAN package pacman which has the p_load
function to install one or more packages (but only if necessary) and then load them.
还有CRAN包pacman,它具有p_load函数来安装一个或多个包(但仅在必要时),然后加载它们。
#5
9
# Function to check whether package is installed
is.installed <- function(mypkg){
is.element(mypkg, installed.packages()[,1])
}
# check if package "hydroGOF" is installed
if (!is.installed("hydroGOF")){
install.packages("hydroGOF")
}
#6
6
I found a packages
script somewhere that I always put in every script to load my libraries. It will do all your library handling (downloading, installing and loading), and only when needed.
我在某个地方找到了一个包脚本,我总是把它放在每个脚本中以加载我的库。它将完成您的所有库处理(下载、安装和加载),并且只在需要时进行。
# Install function for packages
packages<-function(x){
x<-as.character(match.call()[[2]])
if (!require(x,character.only=TRUE)){
install.packages(pkgs=x,repos="http://cran.r-project.org")
require(x,character.only=TRUE)
}
}
packages(ggplot2)
packages(reshape2)
packages(plyr)
# etc etc
#7
4
Or a massively overticked example from drknexus/repsych
on github, glibrary. There are almost certainly more efficient and better ways to to do this, but I programmed it a long while back and it basically works.
或者是github上的drknexus/repsych的一个超大的例子。几乎肯定有更有效和更好的方法来做这个,但是我编程了很长一段时间,它基本上起作用了。
- It works even if a repo hasn't been selected by taking the default cloud option if available. If you are on an older version of R it will roll back and pick a mirror based on country code.
- 即使repo没有通过默认的云选项(如果可用)进行选择,它也是有效的。如果你使用的是旧版本的R,它会回滚并根据国家代码选择镜像。
- It tries to load the library (this step could be made more efficient using some of the methods above)
- If it fails, it will try to install it
- 如果失败,它将尝试安装它。
- If the install fails it will notify you which packages failed to install
- 如果安装失败,它会通知您哪些软件包没有安装。
- 它试图加载这个库(使用上面的一些方法可以提高这个步骤的效率),如果它失败了,它将尝试安装它,如果安装失败,它会通知你哪些软件包没有安装。
- That is right, packages, multiple packages can be loaded/installed in a single pass along with their dependencies (at least usually, there may be a bug here).
- 这是正确的,包,多个包可以被装载/安装在一个单独的传递和它们的依赖(至少通常,这里可能有一个bug)。
e.g.: glibrary(xtable,sos,data.table)
but I don't think it will freak out if you call glibrary("xtable","sos","data.table")
instead. Pushes/pulls/forks welcome.
但是,如果您调用glibrary(“xtable”、“sos”、“data.table”),我不认为它会崩溃。推/拉/叉子的欢迎。
Code for the function:
代码功能:
#' Try to load a library, if that fails, install it, then load it.
#'
#' glibrary short for (get)library.
#' The primary aim of this function is to make loading packages more transparent. Given that we know we want to load a given package, actually fetching it is a formality. glibrary skims past this formality to install the requested package.
#'
#' @export
#' @param ... comma seperated package names
#' @param lib.loc See \code{\link{require}}
#' @param quietly See \code{\link{require}}
#' @param warn.conflicts See \code{\link{require}}
#' @param pickmirror If TRUE, glibrary allows the user to select the mirror, otherwise it auto-selects on the basis of the country code
#' @param countrycode This option is ignored and the first mirror with the substring "Cloud", e.g. the RStudio cloud, is selected. If no mirrors with that substring are identified, glibrary compares this value to results from getCRANmirrors() to select a mirror in the specified country.
#' @return logical; TRUE if glibrary was a success, an error if a package failed to load
#' @note keep.source was an arguement to require that was deprecated in R 2.15
#' @note This warning \code{Warning in install.packages: InternetOpenUrl failed: 'The operation timed out'} indicates that the randomly selected repository is not available. Check your internet connection. If your internet connection is fine, set pickmirror=TRUE and manually select an operational mirror.
#' @examples
#' #glibrary(lattice,MASS) #not run to prevent needless dependency
glibrary <- function(..., lib.loc = NULL, quietly = FALSE, warn.conflicts = TRUE, pickmirror = FALSE, countrycode = "us") {
warningHandle <- function(w) {
if (grepl("there is no package called",w$message,fixed=TRUE)) {
return(FALSE) #not-loadable
} else {
return(TRUE) #loadable
}
}
character.only <- TRUE #this value is locked to TRUE so that the function passes the character value to require and not the variable name thislib
librarynames <- unlist(lapply(as.list(substitute(.(...)))[-1],as.character))
#if package already loaded, remove it from librarynames before processing further
si.res <- sessionInfo()
cur.loaded <- c(si.res$basePkgs,names(si.res$otherPkgs)) #removed names(si.res$loadedOnly) because those are loaded, but not attached, so glibrary does need to handle them.
librarynames <- librarynames[librarynames %!in% cur.loaded]
success <- vector("logical", length(librarynames))
if (length(success)==0) {return(invisible(TRUE))} #everything already loaded, end.
alreadyInstalled <- installed.packages()[,"Package"]
needToInstall <- !librarynames %in% alreadyInstalled
if (any(needToInstall)) {
if (pickmirror) {chooseCRANmirror()}
if (getOption("repos")[["CRAN"]] == "@CRAN@") {
#Select the first "Cloud" if available
m <- getCRANmirrors(all = FALSE, local.only = FALSE)
URL <- m[grepl("Cloud",m$Name),"URL"][1] #get the first repos with "cloud" in the name
if (is.na(URL)) { #if we did not find the cloud,
#Fall back and use the previous method
message("\nIn repsych:glibrary: Now randomly selecting a CRAN mirror. You may reselect your CRAN mirror with chooseCRANmirror().\n")
#if there is no repository set pick a random one by country code
getCRANmirrors.res <- getCRANmirrors()
foundone <- FALSE #have we found a CRAN mirror yet?
#is it a valid country code?
if (!countrycode %in% getCRANmirrors.res$CountryCode) {
stop("In repsych::glibrary: Invalid countrycode argument")
}
ticker <- 0
while (!foundone) {
ticker <- ticker + 1
URL <- getCRANmirrors.res$URL[sample(grep(countrycode, getCRANmirrors.res$CountryCode), 1)]
host.list <- strsplit(URL, "/")
host.clean <- unlist(lapply(host.list, FUN = function(x) {return(x[3])}))
#make sure we can actually access the package list
if (nrow(available.packages(contrib.url(URL)))!=0) {foundone <- TRUE}
if (ticker > 5) {stop("In repsych::glibrary: Unable to access valid repository. Is the internet connection working?")}
} #end while
} #end else
repos <- getOption("repos")
repos["CRAN"] <- gsub("/$", "", URL[1L])
options(repos = repos)
} #done setting CRAN mirror
#installing packages
installResults <- sapply(librarynames[needToInstall],install.packages)
#checking for successful install
needToInstall <- !librarynames %in% installed.packages()[,"Package"]
if (any(needToInstall)) {
stop(paste("In repsych::glibrary: Could not download and/or install: ",paste(librarynames[needToInstall],collapse=", "),"... glibrary stopped.",sep=""))
} # done reporting any failure to install
} #done if any needed to install
#message("In repsych::glibrary: Attempting to load requested packages...\n")
#success <- tryCatch(
success <- sapply(librarynames,require, lib.loc = lib.loc, quietly = FALSE, warn.conflicts = warn.conflicts, character.only = TRUE)
#, warning=warningHandle) #end tryCatch
if(length(success) != length(librarynames)) {stop("A package failed to return a success in glibrary.")}
if (all(success)) {
#message("In repsych::glibrary: Success!")
return(invisible(TRUE))
} else {
stop(paste("\nIn repsych::glibrary, unable to load: ", paste(librarynames[!success]),
collapse = " "))
}
stop("A problem occured in glibrary") #shouldn't get this far down, all returns should be made.
}
NULL
#8
4
requiredPackages = c('plyr','ggplot2','ggtern')
for(p in requiredPackages){
if(!require(p,character.only = TRUE)) install.packages(p)
library(p,character.only = TRUE)
}
#9
3
The solution I used derived from Sacha Epskamp and Shuguang's input. Here's the function:
我使用的解决方案是由Sacha Epskamp和Shuguang提供的。的功能:
instalaPacotes <- function(pacote) {
if (!pacote %in% installed.packages()) install.packages(pacote)
}
It works silently, echoing nothing if package "pacote" is already installed and installing it otherwise. Don't forget to write the name of the package between quotes!
它可以安静地工作,如果软件包“pacote”已经安装并安装了它,它就不会有任何回音。不要忘记在引号之间写包的名称!
#10
3
I have implemented the function to install and load required R packages silently. Hope might help. Here is the code:
我已经实现了在静默中安装和加载所需的R包的功能。希望可以帮助。这是代码:
# Function to Install and Load R Packages
Install_And_Load <- function(Required_Packages)
{
Remaining_Packages <- Required_Packages[!(Required_Packages %in% installed.packages()[,"Package"])];
if(length(Remaining_Packages))
{
install.packages(Remaining_Packages);
}
for(package_name in Required_Packages)
{
library(package_name,character.only=TRUE,quietly=TRUE);
}
}
# Specify the list of required packages to be installed and load
Required_Packages=c("ggplot2", "Rcpp");
# Call the Function
Install_And_Load(Required_Packages);
#11
2
How about trying this?
在这个怎么样?
#will install the pROC library if you don't have it
if(!is.element('pROC', installed.packages()[,1]))
{install.packages('pROC')
}else {print("pROC library already installed")}
#12
1
Why not just delete the line from the script? If the end-user doesn't have the smarts to install xtable
as needed, you've got bigger problems :-( . That said, check out installed.packages()
为什么不直接从脚本中删除线呢?如果最终用户没有必要的smarts安装xtable,那么您将遇到更大的问题:-(。也就是说,签出installed.packages()
Edit: dang, Ninja'd by ONE minute!
党,忍者们一分钟!
Edit: a general suggestion: load the package sos
, and you'll find it very easy to get answers to a lot of "is there a function that does XXXXX" questions.
编辑:一个一般性的建议:加载软件包sos,你会发现很容易得到很多“有一个功能,做XXXXX”的问题。
#13
1
I suggest a more lightweight solution using system.file
.
我建议使用system.file更轻量级的解决方案。
is_inst <- function(pkg) {
nzchar(system.file(package = pkg))
}
is_inst2 <- function(pkg) {
pkg %in% rownames(installed.packages())
}
library(microbenchmark)
microbenchmark(is_inst("aaa"), is_inst2("aaa"))
## Unit: microseconds
## expr min lq mean median uq max neval
## is_inst("aaa") 22.284 24.6335 42.84806 34.6815 47.566 252.568 100
## is_inst2("aaa") 1099.334 1220.5510 1778.57019 1401.5095 1829.973 17653.148 100
microbenchmark(is_inst("ggplot2"), is_inst2("ggplot2"))
## Unit: microseconds
## expr min lq mean median uq max neval
## is_inst("ggplot2") 336.845 386.660 459.243 431.710 483.474 867.637 100
## is_inst2("ggplot2") 1144.613 1276.847 1507.355 1410.054 1656.557 2747.508 100
#14
0
This should do it. You can make required.packages
a vector if you need to check for more than one.
这应该这样做。你可以要求。如果需要检查多个,则打包一个向量。
required.packages <- "data.table"
new.packages <- required.packages[!(required.packages %in% installed.packages()[,"Package"])]
if(length(new.packages)) install.packages(new.packages)
#15
0
Reading everyone's responses, I took some hints here and there and created mine. Actually very similar to most though.
阅读每个人的回答,我在这里和那里得到一些提示,并创建了我的。实际上非常类似。
## These codes are used for installing packages
# function for installing needed packages
installpkg <- function(x){
if(x %in% rownames(installed.packages())==FALSE) {
if(x %in% rownames(available.packages())==FALSE) {
paste(x,"is not a valid package - please check again...")
} else {
install.packages(x)
}
} else {
paste(x,"package already installed...")
}
}
# install necessary packages
required_packages <- c("sqldf","car")
lapply(required_packages,installpkg)
#16
0
Looked at my old function, updated it using tips above and this is what i got.
看看我的旧函数,用上面的提示更新它,这就是我得到的。
# VERSION 1.0
assign("installP", function(pckgs){
ins <- function(pckg, mc){
add <- paste(c(" ", rep("-", mc+1-nchar(pckg)), " "), collapse = "");
if( !require(pckg,character.only=TRUE) ){
reps <- c("http://lib.stat.cmu.edu/R/CRAN","http://cran.uk.R-project.org");
for (r in reps) try(utils::install.packages(pckg, repos=r), silent=TRUE);
if(!require(pckg,character.only = TRUE)){ cat("Package: ",pckg,add,"not found.\n",sep="");
}else{ cat("Package: ",pckg,add,"installed.\n",sep="");}
}else{ cat("Package: ",pckg,add,"is loaded.\n",sep=""); } }
invisible(suppressMessages(suppressWarnings(lapply(pckgs,ins, mc=max(nchar(pckgs)))))); cat("\n");
}, envir=as.environment("dg_base"))
installP(c("base","a","TFX"))
Package: base ------------------- is loaded.
Package: a ---------------------- not found.
Package: TFX -------------------- installed.
#1
116
try: require("xtable")
or "xtable" %in% rownames(installed.packages())
尝试:需要(“xtable”)或“xtable”% rownames(installed.packages())
#2
39
This is a function I often used to check for a package, install it otherwise and load again:
这是一个我经常用来检查包的函数,安装它,然后重新加载:
pkgTest <- function(x)
{
if (!require(x,character.only = TRUE))
{
install.packages(x,dep=TRUE)
if(!require(x,character.only = TRUE)) stop("Package not found")
}
}
Works like pkgTest("xtable")
. It only works if the mirror is set though, but you could enter that in the require
calls.
就像pkgTest(“xtable”)。它只在镜像设置时有效,但是您可以在需要调用的时候输入它。
#3
36
If you want to do it as simply as possible:
如果你想简单地做到这一点:
packages <- c("ggplot2", "dplyr", "Hmisc", "lme4", "arm", "lattice", "lavaan")
if (length(setdiff(packages, rownames(installed.packages()))) > 0) {
install.packages(setdiff(packages, rownames(installed.packages())))
}
Replace the packages listed on the first line by those needed to run your code, and voilà!
将第一行中列出的包替换为运行代码所需的包,这样就可以了!
#4
11
There's also the CRAN package pacman which has the p_load
function to install one or more packages (but only if necessary) and then load them.
还有CRAN包pacman,它具有p_load函数来安装一个或多个包(但仅在必要时),然后加载它们。
#5
9
# Function to check whether package is installed
is.installed <- function(mypkg){
is.element(mypkg, installed.packages()[,1])
}
# check if package "hydroGOF" is installed
if (!is.installed("hydroGOF")){
install.packages("hydroGOF")
}
#6
6
I found a packages
script somewhere that I always put in every script to load my libraries. It will do all your library handling (downloading, installing and loading), and only when needed.
我在某个地方找到了一个包脚本,我总是把它放在每个脚本中以加载我的库。它将完成您的所有库处理(下载、安装和加载),并且只在需要时进行。
# Install function for packages
packages<-function(x){
x<-as.character(match.call()[[2]])
if (!require(x,character.only=TRUE)){
install.packages(pkgs=x,repos="http://cran.r-project.org")
require(x,character.only=TRUE)
}
}
packages(ggplot2)
packages(reshape2)
packages(plyr)
# etc etc
#7
4
Or a massively overticked example from drknexus/repsych
on github, glibrary. There are almost certainly more efficient and better ways to to do this, but I programmed it a long while back and it basically works.
或者是github上的drknexus/repsych的一个超大的例子。几乎肯定有更有效和更好的方法来做这个,但是我编程了很长一段时间,它基本上起作用了。
- It works even if a repo hasn't been selected by taking the default cloud option if available. If you are on an older version of R it will roll back and pick a mirror based on country code.
- 即使repo没有通过默认的云选项(如果可用)进行选择,它也是有效的。如果你使用的是旧版本的R,它会回滚并根据国家代码选择镜像。
- It tries to load the library (this step could be made more efficient using some of the methods above)
- If it fails, it will try to install it
- 如果失败,它将尝试安装它。
- If the install fails it will notify you which packages failed to install
- 如果安装失败,它会通知您哪些软件包没有安装。
- 它试图加载这个库(使用上面的一些方法可以提高这个步骤的效率),如果它失败了,它将尝试安装它,如果安装失败,它会通知你哪些软件包没有安装。
- That is right, packages, multiple packages can be loaded/installed in a single pass along with their dependencies (at least usually, there may be a bug here).
- 这是正确的,包,多个包可以被装载/安装在一个单独的传递和它们的依赖(至少通常,这里可能有一个bug)。
e.g.: glibrary(xtable,sos,data.table)
but I don't think it will freak out if you call glibrary("xtable","sos","data.table")
instead. Pushes/pulls/forks welcome.
但是,如果您调用glibrary(“xtable”、“sos”、“data.table”),我不认为它会崩溃。推/拉/叉子的欢迎。
Code for the function:
代码功能:
#' Try to load a library, if that fails, install it, then load it.
#'
#' glibrary short for (get)library.
#' The primary aim of this function is to make loading packages more transparent. Given that we know we want to load a given package, actually fetching it is a formality. glibrary skims past this formality to install the requested package.
#'
#' @export
#' @param ... comma seperated package names
#' @param lib.loc See \code{\link{require}}
#' @param quietly See \code{\link{require}}
#' @param warn.conflicts See \code{\link{require}}
#' @param pickmirror If TRUE, glibrary allows the user to select the mirror, otherwise it auto-selects on the basis of the country code
#' @param countrycode This option is ignored and the first mirror with the substring "Cloud", e.g. the RStudio cloud, is selected. If no mirrors with that substring are identified, glibrary compares this value to results from getCRANmirrors() to select a mirror in the specified country.
#' @return logical; TRUE if glibrary was a success, an error if a package failed to load
#' @note keep.source was an arguement to require that was deprecated in R 2.15
#' @note This warning \code{Warning in install.packages: InternetOpenUrl failed: 'The operation timed out'} indicates that the randomly selected repository is not available. Check your internet connection. If your internet connection is fine, set pickmirror=TRUE and manually select an operational mirror.
#' @examples
#' #glibrary(lattice,MASS) #not run to prevent needless dependency
glibrary <- function(..., lib.loc = NULL, quietly = FALSE, warn.conflicts = TRUE, pickmirror = FALSE, countrycode = "us") {
warningHandle <- function(w) {
if (grepl("there is no package called",w$message,fixed=TRUE)) {
return(FALSE) #not-loadable
} else {
return(TRUE) #loadable
}
}
character.only <- TRUE #this value is locked to TRUE so that the function passes the character value to require and not the variable name thislib
librarynames <- unlist(lapply(as.list(substitute(.(...)))[-1],as.character))
#if package already loaded, remove it from librarynames before processing further
si.res <- sessionInfo()
cur.loaded <- c(si.res$basePkgs,names(si.res$otherPkgs)) #removed names(si.res$loadedOnly) because those are loaded, but not attached, so glibrary does need to handle them.
librarynames <- librarynames[librarynames %!in% cur.loaded]
success <- vector("logical", length(librarynames))
if (length(success)==0) {return(invisible(TRUE))} #everything already loaded, end.
alreadyInstalled <- installed.packages()[,"Package"]
needToInstall <- !librarynames %in% alreadyInstalled
if (any(needToInstall)) {
if (pickmirror) {chooseCRANmirror()}
if (getOption("repos")[["CRAN"]] == "@CRAN@") {
#Select the first "Cloud" if available
m <- getCRANmirrors(all = FALSE, local.only = FALSE)
URL <- m[grepl("Cloud",m$Name),"URL"][1] #get the first repos with "cloud" in the name
if (is.na(URL)) { #if we did not find the cloud,
#Fall back and use the previous method
message("\nIn repsych:glibrary: Now randomly selecting a CRAN mirror. You may reselect your CRAN mirror with chooseCRANmirror().\n")
#if there is no repository set pick a random one by country code
getCRANmirrors.res <- getCRANmirrors()
foundone <- FALSE #have we found a CRAN mirror yet?
#is it a valid country code?
if (!countrycode %in% getCRANmirrors.res$CountryCode) {
stop("In repsych::glibrary: Invalid countrycode argument")
}
ticker <- 0
while (!foundone) {
ticker <- ticker + 1
URL <- getCRANmirrors.res$URL[sample(grep(countrycode, getCRANmirrors.res$CountryCode), 1)]
host.list <- strsplit(URL, "/")
host.clean <- unlist(lapply(host.list, FUN = function(x) {return(x[3])}))
#make sure we can actually access the package list
if (nrow(available.packages(contrib.url(URL)))!=0) {foundone <- TRUE}
if (ticker > 5) {stop("In repsych::glibrary: Unable to access valid repository. Is the internet connection working?")}
} #end while
} #end else
repos <- getOption("repos")
repos["CRAN"] <- gsub("/$", "", URL[1L])
options(repos = repos)
} #done setting CRAN mirror
#installing packages
installResults <- sapply(librarynames[needToInstall],install.packages)
#checking for successful install
needToInstall <- !librarynames %in% installed.packages()[,"Package"]
if (any(needToInstall)) {
stop(paste("In repsych::glibrary: Could not download and/or install: ",paste(librarynames[needToInstall],collapse=", "),"... glibrary stopped.",sep=""))
} # done reporting any failure to install
} #done if any needed to install
#message("In repsych::glibrary: Attempting to load requested packages...\n")
#success <- tryCatch(
success <- sapply(librarynames,require, lib.loc = lib.loc, quietly = FALSE, warn.conflicts = warn.conflicts, character.only = TRUE)
#, warning=warningHandle) #end tryCatch
if(length(success) != length(librarynames)) {stop("A package failed to return a success in glibrary.")}
if (all(success)) {
#message("In repsych::glibrary: Success!")
return(invisible(TRUE))
} else {
stop(paste("\nIn repsych::glibrary, unable to load: ", paste(librarynames[!success]),
collapse = " "))
}
stop("A problem occured in glibrary") #shouldn't get this far down, all returns should be made.
}
NULL
#8
4
requiredPackages = c('plyr','ggplot2','ggtern')
for(p in requiredPackages){
if(!require(p,character.only = TRUE)) install.packages(p)
library(p,character.only = TRUE)
}
#9
3
The solution I used derived from Sacha Epskamp and Shuguang's input. Here's the function:
我使用的解决方案是由Sacha Epskamp和Shuguang提供的。的功能:
instalaPacotes <- function(pacote) {
if (!pacote %in% installed.packages()) install.packages(pacote)
}
It works silently, echoing nothing if package "pacote" is already installed and installing it otherwise. Don't forget to write the name of the package between quotes!
它可以安静地工作,如果软件包“pacote”已经安装并安装了它,它就不会有任何回音。不要忘记在引号之间写包的名称!
#10
3
I have implemented the function to install and load required R packages silently. Hope might help. Here is the code:
我已经实现了在静默中安装和加载所需的R包的功能。希望可以帮助。这是代码:
# Function to Install and Load R Packages
Install_And_Load <- function(Required_Packages)
{
Remaining_Packages <- Required_Packages[!(Required_Packages %in% installed.packages()[,"Package"])];
if(length(Remaining_Packages))
{
install.packages(Remaining_Packages);
}
for(package_name in Required_Packages)
{
library(package_name,character.only=TRUE,quietly=TRUE);
}
}
# Specify the list of required packages to be installed and load
Required_Packages=c("ggplot2", "Rcpp");
# Call the Function
Install_And_Load(Required_Packages);
#11
2
How about trying this?
在这个怎么样?
#will install the pROC library if you don't have it
if(!is.element('pROC', installed.packages()[,1]))
{install.packages('pROC')
}else {print("pROC library already installed")}
#12
1
Why not just delete the line from the script? If the end-user doesn't have the smarts to install xtable
as needed, you've got bigger problems :-( . That said, check out installed.packages()
为什么不直接从脚本中删除线呢?如果最终用户没有必要的smarts安装xtable,那么您将遇到更大的问题:-(。也就是说,签出installed.packages()
Edit: dang, Ninja'd by ONE minute!
党,忍者们一分钟!
Edit: a general suggestion: load the package sos
, and you'll find it very easy to get answers to a lot of "is there a function that does XXXXX" questions.
编辑:一个一般性的建议:加载软件包sos,你会发现很容易得到很多“有一个功能,做XXXXX”的问题。
#13
1
I suggest a more lightweight solution using system.file
.
我建议使用system.file更轻量级的解决方案。
is_inst <- function(pkg) {
nzchar(system.file(package = pkg))
}
is_inst2 <- function(pkg) {
pkg %in% rownames(installed.packages())
}
library(microbenchmark)
microbenchmark(is_inst("aaa"), is_inst2("aaa"))
## Unit: microseconds
## expr min lq mean median uq max neval
## is_inst("aaa") 22.284 24.6335 42.84806 34.6815 47.566 252.568 100
## is_inst2("aaa") 1099.334 1220.5510 1778.57019 1401.5095 1829.973 17653.148 100
microbenchmark(is_inst("ggplot2"), is_inst2("ggplot2"))
## Unit: microseconds
## expr min lq mean median uq max neval
## is_inst("ggplot2") 336.845 386.660 459.243 431.710 483.474 867.637 100
## is_inst2("ggplot2") 1144.613 1276.847 1507.355 1410.054 1656.557 2747.508 100
#14
0
This should do it. You can make required.packages
a vector if you need to check for more than one.
这应该这样做。你可以要求。如果需要检查多个,则打包一个向量。
required.packages <- "data.table"
new.packages <- required.packages[!(required.packages %in% installed.packages()[,"Package"])]
if(length(new.packages)) install.packages(new.packages)
#15
0
Reading everyone's responses, I took some hints here and there and created mine. Actually very similar to most though.
阅读每个人的回答,我在这里和那里得到一些提示,并创建了我的。实际上非常类似。
## These codes are used for installing packages
# function for installing needed packages
installpkg <- function(x){
if(x %in% rownames(installed.packages())==FALSE) {
if(x %in% rownames(available.packages())==FALSE) {
paste(x,"is not a valid package - please check again...")
} else {
install.packages(x)
}
} else {
paste(x,"package already installed...")
}
}
# install necessary packages
required_packages <- c("sqldf","car")
lapply(required_packages,installpkg)
#16
0
Looked at my old function, updated it using tips above and this is what i got.
看看我的旧函数,用上面的提示更新它,这就是我得到的。
# VERSION 1.0
assign("installP", function(pckgs){
ins <- function(pckg, mc){
add <- paste(c(" ", rep("-", mc+1-nchar(pckg)), " "), collapse = "");
if( !require(pckg,character.only=TRUE) ){
reps <- c("http://lib.stat.cmu.edu/R/CRAN","http://cran.uk.R-project.org");
for (r in reps) try(utils::install.packages(pckg, repos=r), silent=TRUE);
if(!require(pckg,character.only = TRUE)){ cat("Package: ",pckg,add,"not found.\n",sep="");
}else{ cat("Package: ",pckg,add,"installed.\n",sep="");}
}else{ cat("Package: ",pckg,add,"is loaded.\n",sep=""); } }
invisible(suppressMessages(suppressWarnings(lapply(pckgs,ins, mc=max(nchar(pckgs)))))); cat("\n");
}, envir=as.environment("dg_base"))
installP(c("base","a","TFX"))
Package: base ------------------- is loaded.
Package: a ---------------------- not found.
Package: TFX -------------------- installed.