当动态输入选择导致内联 flexdashboard 图表注释中嵌入的反应对象出现问题时,更好的错误处理

better error handling when dynamic input selections cause problems for reactive objects embedded in inline flexdashboard chart notes

当动态过滤和分面在数据中产生问题时,如何避免在我的 flexdashboard 图表注释中出现错误消息?例如,这是一个 select 输入导致没有数据的示例。

---
title: "Example"
runtime: shiny
output:
  flexdashboard::flex_dashboard:
    vertical_layout: fill
---


```{r}
  library(tidyverse)
  library(flexdashboard)
```


### Chart 1

```{r}

df <- fortify(forecast::gold)

fillCol(height = "100%", flex = c(1, NA), 
    plotOutput("plot", height = "100%"),
    wellPanel(
      tags$style(".well {background-color:#ffffff; border-color:#ffffff;}"),
      radioButtons("myInput", label = NULL,
        choices = list("All" = "all",
                       "Problematic filtering" = "filter"),
        selected = "all", inline=T)
      )
    )

output$plot <- renderPlot({
  ggplot(df, aes(x, y)) + 
         geom_line() 
})

notes <- reactive({
  if (input$myInput=="all") {
    df %>%
      summarise(mean = mean(y, na.rm=TRUE)) %>%
      pull(mean)
  } else {
    df %>%
      filter(x==0) %>%
      summarise(mean = mean(y, na.rm=TRUE)) %>%
      pull(mean)
    }
  })

# new attempt
notes_ <- reactive({

notes <- notes()

  if (exists("notes") & !is.na(notes) & !is.nan(notes)) {
    print(notes)
    } else {
    print("[not available]")
    }

  })
```

> The mean is `r notes_`.

尝试

这会打印“[不可用]”(上面已集成)。有没有更好的方法?

# new attempt
notes_ <- reactive({

notes <- notes()

  if (exists("notes") & !is.na(notes) & !is.nan(notes)) {
    print(notes)
    } else {
    print("[not available]")
    }

  })
```

> The mean is `r notes_`.

这会打印“[不可用]”。接受更好的解决方案...

---
title: "Example"
runtime: shiny
output:
  flexdashboard::flex_dashboard:
    vertical_layout: fill
---


```{r}
  library(tidyverse)
  library(flexdashboard)
```


### Chart 1

```{r}

df <- fortify(forecast::gold)

fillCol(height = "100%", flex = c(1, NA), 
    plotOutput("plot", height = "100%"),
    wellPanel(
      tags$style(".well {background-color:#ffffff; border-color:#ffffff;}"),
      radioButtons("myInput", label = NULL,
        choices = list("All" = "all",
                       "Problematic filtering" = "filter"),
        selected = "all", inline=T)
      )
    )

output$plot <- renderPlot({
  ggplot(df, aes(x, y)) + 
         geom_line() 
})

notes <- reactive({
  if (input$myInput=="all") {
    df %>%
      summarise(mean = mean(y, na.rm=TRUE)) %>%
      pull(mean)
  } else {
    df %>%
      filter(x==0) %>%
      summarise(mean = mean(y, na.rm=TRUE)) %>%
      pull(mean)
    }
  })

notes_ <- reactive({

notes <- notes()

  if (exists("notes") & !is.na(notes) & !is.nan(notes)) {
    print(notes)
    } else {
    print("[not available]")
    }

  })
```

> The mean is `r notes_`.