代码之家  ›  专栏  ›  技术社区  ›  Doug Fir

ggplot with tryCatch:如果在表达式过程中出现错误,则希望使用空白绘图

  •  1
  • Doug Fir  · 技术社区  · 4 年前

    x %>% dput
    structure(list(date = structure(c(18782, 18783, 18784, 18785, 
    18786, 18787, 18789, 18791, 18792, 18793, 18795, 18797, 18798, 
    18799, 18801, 18803, 18805, 18806), class = "Date"), `Expired Trials` = c(3L, 
    1L, 1L, 1L, 3L, 3L, 1L, 1L, 1L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 
    0L), `Trial Sign Ups` = c(3L, 1L, 1L, 2L, 3L, 4L, 1L, 1L, 1L, 
    1L, 2L, 1L, 3L, 2L, 2L, 1L, 1L, 1L), `Total Site Conversions` = c(3, 
    1, 1, 2, 3, 4, 1, 1, 1, 1, 2, 1, 3, 2, 2, 1, 1, 1), `Site Conversion Rate` = c(NA_real_, 
    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, 
    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, 
    NA_real_, NA_real_, NA_real_), `Trial to Paid Conversion Rate` = c(NA_real_, 
    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, 
    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, 
    NA_real_, NA_real_, NA_real_)), row.names = c(NA, -18L), class = c("tbl_df", 
    "tbl", "data.frame"))
    

    x %>% 
         ggplot(aes(date, Sessions)) +
         geom_col(na.rm = T) +
         geom_line(aes(y = `Site Conversion Rate`), na.rm = T)
    Error in FUN(X[[i]], ...) : object 'Sessions' not found
    

    尝试:

    tryCatch(expr = {x %>% 
        ggplot(aes(date, Sessions)) +
        geom_col(na.rm = T) +
        geom_line(aes(y = `Site Conversion Rate`), na.rm = T)
    }, 
    error = function(e) {message(''); print(e)},
    finally = {ggplot() + theme_void()})
    

    但是,这还是吐出了错误,想要/期待一个空白的情节。

    我该怎么做?

    1 回复  |  直到 4 年前
        1
  •  2
  •   akrun    4 年前

    if/else 带的表达式 all i、 e.我们只策划 if

    nm1 <- c("date", "Sessions", "Site Conversion Rate")
    if(!all(nm1 %in% names(x))) {
         message("Not all columns are found")
         ggplot()
        } else {x %>% 
         ggplot(aes(date, Sessions)) +
         geom_col(na.rm = TRUE) +
         geom_line(aes(y = `Site Conversion Rate`), na.rm = TRUE)}
    

    或者另一个选择是 possibly 指定 otherwise

    library(purrr)
    f1 <- function(x) {
      p1 <- x %>% 
          ggplot(aes(date, Sessions)) +
          geom_col(na.rm = TRUE) +
          geom_line(aes(y = `Site Conversion Rate`), na.rm = TRUE)
      print(p1)
     
     }
    f1p <- possibly(f1, otherwise = ggplot())
    

    f1p(x)
    

    -输出

    enter image description here


    tryCatch

    tryCatch(expr = {print(x %>% 
        ggplot(aes(date, Sessions)) +
        geom_col(na.rm = T) +
        geom_line(aes(y = `Site Conversion Rate`), na.rm = TRUE))
    }, 
    error = function(e) {message(''); print(e)},
    finally = {
           ggplot() + 
              theme_void()
    })
    <simpleError in FUN(X[[i]], ...): object 'Sessions' not found>