如何进行安装。如果不能安装R包,那么包会返回一个错误吗?

时间:2021-02-27 21:37:48

install.packages() returns a warning if a package cannot be installed (for instance, if it is unavailable); for example:

软件包()返回一个警告,如果软件包不能安装(例如,如果它不可用);例如:

install.packages("notapackage")

(EDIT: I'd like to throw an error regardless of the reason the package cannot be installed, not just this example case of a missing package).

(编辑:我想抛出一个错误,不管这个包无法安装的原因是什么,而不仅仅是这个丢失包的例子)。

I am running the install.packages command in a script, and I would like it to trigger a proper error and exit execution. I don't see an obvious option inside install.packages for handling this behavior. Any suggestions?

我正在运行安装。将命令打包到脚本中,我希望它触发一个正确的错误并退出执行。我在install中没有看到明显的选项。用于处理此行为的包。有什么建议吗?

2 个解决方案

#1


4  

The R function WithCallingHandlers() lets us handle any warnings with an explicitly defined function. For instance, we can tell the R to stop if it receives any warnings (and return the warning message as an error message).

带有callinghandlers()的R函数允许我们使用显式定义的函数处理任何警告。例如,如果R收到任何警告,我们可以告诉它停止(并将警告消息作为错误消息返回)。

withCallingHandlers(install.packages("notapackage"),
                    warning = function(w) stop(w))

I am guessing that this is not ideal, since presumably a package could install successfully but still throw a warning; but haven't encountered that case. As Dirk suggests, testing require for the package is probably more robust.

我猜这并不理想,因为一个包可以成功安装,但仍然会抛出一个警告;但还没有遇到这种情况。正如Dirk所建议的,对包的测试要求可能更加健壮。

#2


0  

Expanding on the quick comment:

扩展快速评论:

R> AP <- available.packages()
R> "notapackage" %in% AP[,1]      # expected to yield FALSE
[1] FALSE
R> "digest" %in% AP[,1]           # whereas this should be TRUE
[1] TRUE
R> 

#1


4  

The R function WithCallingHandlers() lets us handle any warnings with an explicitly defined function. For instance, we can tell the R to stop if it receives any warnings (and return the warning message as an error message).

带有callinghandlers()的R函数允许我们使用显式定义的函数处理任何警告。例如,如果R收到任何警告,我们可以告诉它停止(并将警告消息作为错误消息返回)。

withCallingHandlers(install.packages("notapackage"),
                    warning = function(w) stop(w))

I am guessing that this is not ideal, since presumably a package could install successfully but still throw a warning; but haven't encountered that case. As Dirk suggests, testing require for the package is probably more robust.

我猜这并不理想,因为一个包可以成功安装,但仍然会抛出一个警告;但还没有遇到这种情况。正如Dirk所建议的,对包的测试要求可能更加健壮。

#2


0  

Expanding on the quick comment:

扩展快速评论:

R> AP <- available.packages()
R> "notapackage" %in% AP[,1]      # expected to yield FALSE
[1] FALSE
R> "digest" %in% AP[,1]           # whereas this should be TRUE
[1] TRUE
R>