我试图找到一个简单的方法,使install.packages()
抛出一个错误,如果它失败(而不仅仅是一个警告)。
我已经试过了
设置options(warn=2)
将警告转换为错误。例子:
options(warn=2)
warning()
# Error: (converted from warning)
我预料这会出错:
install.packages('thispackagedoesntexist')
# Warning in install.packages :
# package ‘thispackagedoesntexist’ is not available for this version of R
#
# A version of this package for your version of R might be available elsewhere,
# see the ideas at
# https://cran.r-project.org/doc/manuals/r-patched/R-admin.html#Installing-packages
但它仍然只是给出一个警告(没有错误)。
问题如何使install.packages()在任何类型的失败时出错(而不是简单地警告)?
注意:
- 有一些很好的方法使install.packages()错误而不是警告,但我正在寻找一些更轻量级的东西,最好不安装其他包,
options()
将很好地实现(如果我能让它工作)。
这是RStudio的一个"特性"。
首先我想知道为什么警告不是用红色打印的。然后我看了看install.packages
(在RStudio中),看到了这个:
> install.packages
function (...)
.rs.callAs(name, hook, original, ...)
<environment: 0x1408432c8>
> getAnywhere(.rs.callAs)
A single object matching ‘.rs.callAs’ was found
It was found in the following places
tools:rstudio
with value
function (name, f, ...)
{
withCallingHandlers(tryCatch(f(...), error = function(e) {
cat("Error in ", name, " : ", e$message, "n", sep = "")
}), warning = function(w) {
if (getOption("warn") >= 0)
cat("Warning in ", name, " :n ", w$message, "n",
sep = "")
invokeRestart("muffleWarning")
})
}
<environment: 0x1181b4928>
查看如何处理警告以及如何打印"警告";实际上不是一个警告,但cat
输出?
如果我在Rgui中运行你的代码,我看到如下:
> options(warn=2)
> install.packages('thispackagedoesntexist')
Error: (converted from warning) package ‘thispackagedoesntexist’ is not available for this version of R
A version of this package for your version of R might be available elsewhere,
see the ideas at
https://cran.r-project.org/doc/manuals/r-patched/R-admin.html#Installing-packages
所以,我建议你去找RStudio开发人员,抱怨他们使用cat
误导性地打印&;error &;和"warnings".
你可以避免RStudio对install.packages
的屏蔽:
> options(warn=2)
> utils::install.packages('thispackagedoesntexist')
Error: (converted from warning) package ‘thispackagedoesntexist’ is not available for this version of R
A version of this package for your version of R might be available elsewhere,
see the ideas at
https://cran.r-project.org/doc/manuals/r-patched/R-admin.html#Installing-packages