Search code examples
rshinyflexdashboard

Flexdashboard: Pass reactive value to chart-title


In the package flexdashboard the chart titles (headers for cells in the grid) are made via 3 hash marks (e.g., ### Chart title here). I want to pass a reactive value to this header. Normally one could define a UI and push that (https://stackoverflow.com/a/48118297/1000343) but the hash marks are what tell the knitting that this is a chart-title. I also thought about passing the reactive value using in-line code (e.g., `r CODE HERE`) as seen in the MWE below. You can use inline text for chart-titles but not when it contains reactive values. This results in the error:

Error in as.vector: cannot coerce type 'closure' to vector of type 'character'

In this case how could I pass the month in as a chart.title?

MWE (removing last line allows this to run)

---
title: "test"
output: flexdashboard::flex_dashboard
runtime: shiny
---

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

Inputs {.sidebar}
-------------------------------------

```{r}
selectInput(
    "month", 
    label = "Pick a Month",
    choices = month.abb, 
    selected = month.abb[2]
)

getmonth <- reactive({
    input$month
})

renderText({getmonth()})
```  

Column  
-------------------------------------

### `r sprintf('Box 1 (%s)', month.abb[1])`


### `r sprintf('Box 2 (%s)', renderText({getmonth()}))`

Solution

  • The error that occurred was not part of flexdashboard being unable to render dynamic content but rather sprintf not being able to format the closure, that is renderText.

    You only have to make the formatting part of your reactive and you're fine.

    ---
    title: "test"
    output: flexdashboard::flex_dashboard
    runtime: shiny
    ---
    
    ```{r}
    library(flexdashboard)
    library(shiny)
    ```
    
    Inputs {.sidebar}
    -------------------------------------
    
    ```{r}
    selectInput(
      "month", 
      label = "Pick a Month",
      choices = month.abb, 
      selected = month.abb[2]
    )
    
    getmonth <- reactive({
      sprintf('Box 2 (%s)', input$month)
    })
    
    renderText({getmonth()})
    ```  
    
    Column  
    -------------------------------------
    
    ### `r renderText(getmonth())`