r - 正确使用 tryCatch 跳过绘图错误
问题描述
这是这个问题的后续问题,没有得到任何关注。purrr::possibly
我现在意识到这与具体无关,因为tryCatch
也不像我想的那样工作。
我正在尝试编写一个函数,该函数将运行任何其他任意函数而不会引发错误。这可能不是一个好习惯,但我想了解为什么这不起作用:
library(ggplot2)
## function I thought I could use to run other functions safely
safe_plot <- function(.FUN, ...) {
tryCatch({
.FUN(...)
},
error = function(e) {
message(e)
print("I have got passed the error")
})
}
## Simple plot function
plot_fun <- function(df) {
ggplot(df, aes(xvar, yvar)) +
geom_point()
}
## Works for good data
some_data <- data.frame(xvar = 1:10, yvar = 1:10)
safe_plot(.FUN = plot_fun, df = some_data)
## Works here for data that is not defined:
> safe_plot(.FUN = plot_fun, df = not_defined)
object 'not_defined' not found[1] " I have got passed the error"
## Falls over for an empty data frame
empty_data <- data.frame()
safe_plot(.FUN = plot_fun, df = empty_data)
## Why does't this get past this error and print the message?
> safe_plot(.FUN = plot_fun, df = empty_data)
Error in FUN(X[[i]], ...) : object 'xvar' not found
为什么最后一个调用没有到达 print 语句?我怀疑我在滥用 tryCatch 但我不知道为什么。阅读其他一些问题(1、2)我检查了 tryCatch 返回的类:
> ## What is returned
> empty_data <- data.frame()
> what_is_this <- safe_plot(.FUN = plot_fun, df = empty_data)
> what_is_this
Error in FUN(X[[i]], ...) : object 'xvar' not found
> class(what_is_this)
[1] "gg" "ggplot"
所以在上面的 plot 函数ggplot(df,
中不会失败,因为有一个df
of empty_data
。错误必须发生在aes(xar,
. 但是为什么这不返回错误类而是返回一个ggplot呢?
解决方案
推荐阅读
- python - 由于不同的字符编码,查找唯一元素的代码会给出重复的元素
- scala - 尾递归和按名称/值调用
- python - 在递归排列代码中将输出列表作为参数传递是否很好
- wordpress - 我需要帮助来获取外部 url 来显示,就好像它是我网站的一部分一样
- javascript - 启动自己的网站时如何隐藏切换侧边栏?
- php - 如何修复致命错误:未捕获的错误:调用字符串上的成员函数 children()
- java - 如何在 gRPC 中为 Java 手动生成客户端和服务器代码?
- python - 对流程时间戳数据进行数据分析以发现瓶颈和模式
- php - 当我使用 android retrofit2 将 uuid 发布(发送)到服务器时,我得到了不同的号码
- mysql - 存储插入行的时间并且在更新时不会更改它的字段