如何自动发现软件包安装失败?

时间:2018-08-02 18:05:59

标签: r cran

我想从mran快照安装旧软件包。我正在使用以下命令:

tryCatch({
  resp <- install.packages(pkgs = "https://cran.microsoft.com/snapshot/2016-12-05/bin/windows/contrib/3.4/car_2.1-4.zip", 
                           repos = NULL, 
                           dependencies = FALSE, 
                           type = "win.binary")
},
warning = function(e) {
  print("ITERATE - WARNING")
},
error = function(e) {
  print("ITERATE - ERROR")
})

我知道我可以使用版本或devtools之类的软件包。 tryCatch在这里不是错误的。问题是我是否可以尝试/捕捉它?

我知道我可以检查url之前是否存在,甚至可以下载以下文件:

tryCatch({
  download.file("https://cran.microsoft.com/snapshot/2016-12-05/bin/windows/contrib/3.4/car_2.1-4.zip", destfile = "car_2.1-4.zip")
},
error = function(e) {
  print("ITERATE - ERROR")
})

但这不是我正在寻找的解决方案。我想确定此功能失败,然后以某种方式处理它。

  

install.packages()

有人可以给我一些提示吗?

1 个答案:

答案 0 :(得分:0)

如果您不能捕获此错误,则只能假设您使用的是Rstudio,而不仅仅是R。

使用utils::install.packages()代替Rstudio版本。

我个人最喜欢的方法是。

##' Catch *and* save both errors and warnings, and in the case of
##' a warning, also keep the computed result.
##'
##' @title tryCatch both warnings (with value) and errors
##' @param expr an \R expression to evaluate
##' @return a list with 'value' and 'warning', where
##'   'value' may be an error caught.
##' @author Martin Maechler;
##' Copyright (C) 2010-2012  The R Core Team
tryCatch.W.E <- function(expr)
{
    W <- NULL
    w.handler <- function(w){ # warning handler
        W <<- w
        invokeRestart("muffleWarning")
    }
    list(value = withCallingHandlers(tryCatch(expr, error = function(e) e),
                                     warning = w.handler),
         warning = W)
}

 tryme <- tryCatch.W.E({utils::install.packages(pkgs = "https://cran.microsoft.com/snapshot/2016-12-05/bin/windows/contrib/3.4/car_2.1-4.zip", 
                          repos = NULL, 
                          dependencies = FALSE, 
                          type = "win.binary")})

然后,tryme中将出现您的错误,这将使您可以继续前进,而不会遇到困难的stop

相关问题