【发布时间】:2021-02-25 07:52:44
【问题描述】:
我有一个函数运算符来处理绘图错误:
library(ggplot2)
library(dplyr)
handle_plot_error <- function(f) {
tryCatch(
f,
error = function(e) plot_error(e)
)
}
plot_error <- function(error) {
ggplot(
tibble(text = str_wrap(error, 80)),
aes(x = 1, y = 1, label = text)
) +
geom_text(color = "red") +
theme_void()
}
我还有一个创建情节方面的功能:
plot_facet <- function(df) {
df %>%
ggplot(aes(cyl, mpg)) +
geom_line() +
facet_grid(~am)
}
plot_facet 可能会收到一个空数据框作为输入:
handle_plot_error(plot_facet(tibble()))
我的函数无法处理此错误,因此我想改进 handle_plot_error 以包含以下内容:
if(nrow(df) == 0) {
stop("No data available")
}
然后将此错误消息传递给plot_error 函数。
我知道我可以在 plot_facet 中包含 stop 案例,但我更喜欢它在 handle_plot_error 中,因为我将它用于很多绘图功能。
【问题讨论】:
-
不确定我是否理解您的问题。
handle_plot_error用作函数运算符,用于绘制函数并捕获可能的绘图错误并将它们显示在绘图上(我在 Shiny 上使用它)。 -
我突然想到
handle_plot_error函数的主要目的是在闪亮的应用程序中显示有意义的错误消息。否则,您可能不需要在 ggplot2 图中打印错误。如果您的用例是一个闪亮的应用程序,那么您最好使用validate(need())。特别是如果您的data.frame是用户输入,您可以轻松检查nrow(df)== 0是否会在您的图中显示错误(并且所有下游反应都将停止)。
标签: r error-handling try-catch