【问题标题】:How to automatically find that package installation fails?如何自动发现包安装失败?
【发布时间】:2018-08-02 18:05:58
【问题描述】:

我想从 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()

谁能给我一些建议?

【问题讨论】:

    标签: r cran


    【解决方案1】:

    如果你无法捕捉到这一点,我只能假设你使用的是 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

    【讨论】:

    • 太棒了,谢谢!你能解释一下你是如何发现 RStudio 改变了install.packages() 的行为的吗?这让我很惊讶。
    • 另外,当我要去资源时,从两种用法我要去 utils 包。
    • 我基本猜到了。但是当我在源代码处输入 install.packages 和 utils::install.packages 时,我得到了不同的结果。所以我尝试捕获 utils 版本并且它有效。我只能假设 Rstudio 正在做它自己的错误处理来保护我们自己,这就是为什么我们无法在失败时检测到错误。
    • 如果这是您要找的,请接受答案。
    猜你喜欢
    • 2016-12-25
    • 2018-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-01
    • 2021-12-16
    • 2011-03-19
    相关资源
    最近更新 更多