gpt4 book ai didi

r - install.packages() 忽略将警告转换为错误的选项?

转载 作者:行者123 更新时间:2023-12-05 04:20:14 25 4
gpt4 key购买 nike

我正在尝试找到一种简单的方法来使 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() 的好方法 error instead of warning ,但我正在寻找更轻量级的东西,最好不要安装其他软件包,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 误导性地打印“错误”和“警告”。

您可以通过通常的方式避免 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

关于r - install.packages() 忽略将警告转换为错误的选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74568464/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com