【问题标题】:tryCatch in R: returning what was computed in the try block when there is a warningR中的tryCatch:当出现警告时返回try块中计算的内容
【发布时间】:2019-09-17 18:58:27
【问题描述】:
y <- tryCatch({ long_calculation(x) },
               error=function(err){
                 return(NULL)
               },
               warning=function(warn){
                 # how can I return the value of long_calculation(x)
                 # without recomputing?
                 return(long_calculation(x))
               })

所以在 try 块中,它执行的计算需要很长时间。 在警告块中,我仍然想返回计算的内容而不重新计算它。我该怎么做?

可重现的例子:

x <- 1:10000000
x2 <- seq_len(length(x)/17)

y <- tryCatch({ sum(x/x2) },
              error=function(err){
                return(NULL)
              },
              warning=function(warn){
                # how can I return the value of long_calculation(x)
                # without recomputing?
                return(sum(x/x2))
              })

已编辑:

所以我的目标是能够捕获警告消息,这就是为什么我需要为“警告”参数分配一个函数。

【问题讨论】:

  • 哼。你能让你的例子可重现吗?
  • @RomanLuštrik 我添加了一些东西。不确定它是否可重现,因为我想不出任何 sum 会发出警告的情况
  • 我已经让sum(x/x2) 发出警告。 (发出警告的是/,而不是sum)。
  • 我认为你必须处理你的函数,而不是 tryCatch,才能返回部分结果(假设我理解正确)。

标签: r try-catch


【解决方案1】:

如果要让警告消息出现,只需跳过警告函数参数到 tryCatch。

x <- c(1:10000000)
y <- tryCatch({
  warning("Warning!")
  sum(x)
}, error = function(err) return(NULL))

如果你想抑制警告信息,你可以使用suppressWarnings。

x <- c(1:10000000)
y <- tryCatch(suppressWarnings({
  warning("Warning!")
  sum(x)
}), error = function(err) return(NULL))

【讨论】:

  • 其实我想做的是能够捕获警告信息。所以这就是为什么我需要为警告参数分配一个值。然后我仍然想返回计算的内容......而不重新计算它。
【解决方案2】:

这不只是通过删除对警告的任何引用来简化代码的问题吗?

long_calculation <- function(x){
  x2 <- seq_len(length(x)/17)
  sum(x/x2)  
}

x <- 1:10000000

y <- tryCatch({ long_calculation(x) },
              error = function(err) NULL
              )
#Warning message:
#In x/x2 :
#  longer object length is not a multiple of shorter object length

y
#[1] 1141800633

【讨论】:

  • 其实我想做的是能够捕获警告信息。这就是为什么我需要为警告参数分配一个值。然后我仍然想返回计算的内容......而不重新计算它。
猜你喜欢
  • 1970-01-01
  • 2016-06-17
  • 1970-01-01
  • 2012-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多