首页 > 解决方案 > 正确使用 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 但我不知道为什么。阅读其他一些问题(12)我检查了 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, 中不会失败,因为有一个dfof empty_data。错误必须发生在aes(xar, . 但是为什么这不返回错误类而是返回一个ggplot呢?

标签: r

解决方案


推荐阅读