gpt4 book ai didi

r - R : Function returns both error and warning - store both with tryCatch()

转载 作者:行者123 更新时间:2023-12-03 07:54:06 25 4
gpt4 key购买 nike

我在readLines()中使用[R],对于某些URL,它会给我错误以及警告消息:

Error in file(con, "r") : cannot open the connection
In addition: Warning message:
In file(con, "r") : cannot open: HTTP status was '401 Unauthorized'

如您所见,该函数在警告中同时返回一般错误和更具体的解释。目前,我正在使用 tryCatch()和一些行来使用 conditionMessage()打印和存储这些错误。但是,这只存储一般的非信息性错误消息,而实际上我对警告文本更感兴趣。如何存储两者?

工作示例:
errorlist <- NULL

for(i in 1:10){
tryCatch({
readLines("http://www.googl1.com/") # this URL does not exist
}, error = function(e){yy
print(conditionMessage(e))
assign("errorlist", c(errorlist, conditionMessage(e)), envir = .GlobalEnv)
})}

所需的结果将是这样的:
      [,1]                     [,2]                                              
[1,] "cannot open connection" "The server name or address could not be resolved"
[2,] "cannot open connection" "The server name or address could not be resolved"
[3,] "cannot open connection" "The server name or address could not be resolved"
[4,] "cannot open connection" "The server name or address could not be resolved"
[5,] "cannot open connection" "The server name or address could not be resolved"
[6,] "cannot open connection" "The server name or address could not be resolved"
[7,] "cannot open connection" "The server name or address could not be resolved"
[8,] "cannot open connection" "The server name or address could not be resolved"
[9,] "cannot open connection" "The server name or address could not be resolved"
[10,] "cannot open connection" "The server name or address could not be resolved"

最佳答案

您可以通过以下方式将警告变为错误

options(warn=2)

另一方面,这只会在 tryCatch中返回警告(作为错误)。

关于r - R : Function returns both error and warning - store both with tryCatch(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33865867/

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