【发布时间】: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,才能返回部分结果(假设我理解正确)。