17

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?

Tyler Rinker
  • 108,132
  • 65
  • 322
  • 519
  • 2
    Trying to understand the down vote. Seems like someone is down voting everything of mine regardless of question quality. If there is a real reason for the downvote please share so that I can improve. – Tyler Rinker Apr 25 '16 at 13:25
  • 3
    There does seem to be a lot of anonymous downvoting lately, but most of it is for clueless duplicates, This one seems much more bleeding edge and had the addition benefit of eliciting a good answer from a relatively new useR. Kudos to you both. – IRTFM May 22 '16 at 00:27

1 Answers1

21

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 })

```
Michal Majka
  • 5,332
  • 2
  • 29
  • 40