Search code examples
rshinyflexdashboard

Conditional reactive logic shiny based flexdashboard


I am trying to contiditonally do either one type of render (renderPlot) or another (renderText) based on some input. Here's what I tried:

---
title: "Citation Extraction"
output: 
  flexdashboard::flex_dashboard:
    vertical_layout: scroll  
    orientation: rows
    social: menu
    source_code: embed
runtime: shiny
---

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

Sidebar {.sidebar}
=====================================

```{r}
textInput("txt", "What's up?:")
```

Page 1
=====================================

### Chart A

```{r}
urtxt <- reactive({input$txt})

if (nchar(urtxt()) > 20){
    renderPlot({plot(1:10, 1:10)})
} else {
    renderPrint({
        urtxt()   
    })
}
```

But it states:

enter image description here

So I tried adding a reactive around the conditional resulting in returning the function reactive returns.

reactive({
    if (nchar(urtxt()) > 20){
    renderPlot({plot(1:10, 1:10)})
} else {
    renderPrint({
        urtxt()   
    })
}
})

How can I have conditional reactive logic?


Solution

  • To get different kind of output depending on the length of the inputed character string you can do following:

    1) Create a dynamic output uiOutput,

    2) In the reactive environment renderUI, depending on the input, choose kind of the output.

    3) Render the output

    ---
    title: "Citation Extraction"
    output: 
    flexdashboard::flex_dashboard:
    vertical_layout: scroll  
    orientation: rows
    social: menu
    source_code: embed
    runtime: shiny
    ---
    
    ```{r setup, include=FALSE}
    library(flexdashboard)
    library(shiny)
    ```
    
    
    Sidebar {.sidebar}
    =====================================
    
    ```{r, echo = F}
    textInput("txt", "What's up?:", value = "")
    ```
    
    Page 1
    =====================================
    
    ### Chart A
    
    ```{r, echo = F}
    uiOutput("dynamic")
    
    output$dynamic <- renderUI({ 
      if (nchar(input$txt) > 20) plotOutput("plot")
      else textOutput("text")
    })
    
    output$plot <- renderPlot({ plot(1:10, 1:10) })
    output$text <- renderText({ input$txt })
    
    ```