Search code examples
rshinyflexdashboard

Using action button with R flexdashboard


Is it possible to use an action button with R flexdashboard?

for example in the repex below, is it possible to add a button so that the code will run only when the button is displayed?

I can not find documentation on the website https://garrettgman.github.io/rmarkdown/flexdashboard/using.html#html_widgets

and most of the information that are google deals with using action button in a "pure" shiny app not flexdashboard.

---
title: "example"
runtime: shiny
output: 
  flexdashboard::flex_dashboard:
    orientation: columns
    vertical_layout: fill
---

```{r setup, include=FALSE}
library(flexdashboard)
```

Column {data-width=100}
-----------------------------------------------------------------------

### Chart A

```{r}
numericInput("n1", "First number", 10)  


```

Column {data-width=900}
-----------------------------------------------------------------------

### Chart B

```{r}

DT::renderDataTable({
  

x = sample(1:input$n1, size=500, replace=TRUE)
x= as.data.frame(x)

  DT::datatable(x, options = list(
    bPaginate = FALSE
  ))
})


```

Solution

  • Yes, it's possible. You can include an actionButton just as you use the numericInput and then e.g. use the eventReactive programming pattern:

    ---
    title: "example"
    runtime: shiny
    output: 
      flexdashboard::flex_dashboard:
        orientation: columns
        vertical_layout: fill
    ---
    
    ```{r setup, include=FALSE}
    library(flexdashboard)
    ```
    
    Column {data-width=100}
    -----------------------------------------------------------------------
    
    ### Chart A
    
    ```{r}
    numericInput("n1", "First number", 10)  
    actionButton("execute", "Generate data")
    
    ```
    
    Column {data-width=900}
    -----------------------------------------------------------------------
    
    ### Chart B
    
    ```{r}
    table_data <- eventReactive(input$execute, {
      x = sample(1:input$n1, size=500, replace=TRUE)
      as.data.frame(x)
    })
    
    
    DT::renderDataTable({
      req(table_data())
      
      
      
      DT::datatable(table_data(), options = list(
        bPaginate = FALSE
      ))
    })
    
    
    ```