本文介绍了R中的tryCatch块,返回变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我试图了解R中tryCatch的范围和功能。

So, I am trying to understand scope and functionality of tryCatch in R.

以下行:

arima(rep(1,3), order = c(1,0,0))

生成警告和错误,但是在tryCatch块中,仅警告函数返回值。如何获得警告和错误的返回值?

generates both warning and error, however in tryCatch block only warning function returns value. How can I get access to return value of both warning and error?

tryTest = tryCatch(
  {
    arima(rep(1,3), order = c(1,0,0))
  }, 
  warning = function(w) {

    print('this is warning')
    print(w)
    return('return string from warning')
  },
  error = function(e) {
    print('this is error')
    print(e)
    return('return string from error')
  },
  finally = {}
)

print(tryTest)

仅产生:

 "return string from warning"


推荐答案

tryCatch允许您在出错时为变量分配一个值。这是两个最小的示例:

tryCatch in R allows you to assign a value to the variable on error. Here are two minimal examples:

my_logo <- tryCatch(
{
  my_logo <- RCurl::getURLContent("https://invalid.website")
},
error = function(cond){
  my_logo <- "there is no image"
},
finally = {
  #pass
})

> my_logo
[1] "there is no image"

my_var <- tryCatch(
{
  my_var <- "a"/1
},
error = function(cond){
  my_var <- "foo"
},
finally = {
  #pass
})

> my_var
[1] "foo"

同样,您可以返回警告值,如下所示:你已经知道了。您不应编写tryCatch语句,以使其可能同时遇到错误和警告。我什至不知道这是否可能。

Similarly, you can return a value on warning as you already know. You should not write your tryCatch statement such that it could encounter both error and warning at the same time. I am not even sure if that is possible.

编辑:为了完整性,我添加了一个带有警告的示例:

For completeness, I am adding an example with warning:

my_var <- tryCatch(
{
  warning()
  my_var <- "a"/1
},
warning = function(cond){
  print("There was a warning")
  return("bar")
},
error = function(cond){
  my_var <- "foo"
  print("This message will not be printed.")
},
finally = {
  #pass
})
[1] "There was a warning"
> my_var
[1] "bar"

这篇关于R中的tryCatch块,返回变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 07:01