有条件的响应式逻辑,基于Shiny的Flexdashboard。

17

我试图根据一些输入条件,有条件地执行一种渲染类型(renderPlot)或另一种类型(renderText)。 这是我尝试过的:

```r output$outcome <- reactive({ if (input$condition == "plot") { output <- renderPlot({ ... }) } else { output <- renderText({ ... }) } return(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}
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()   
    })
}
```

但是它声明:

enter image description here

因此,我尝试在条件语句周围添加一个响应式,以返回函数 reactive 返回的内容。

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

我如何使用条件反应逻辑?


2
尝试理解负评。似乎有人不论问题的质量如何都在对我的所有内容进行负评。如果有真正的理由,请分享,以便我改进。 - Tyler Rinker
3
最近似乎有很多匿名的投票,但大部分是针对无知的重复问题。这个问题似乎更具先进性,并且还能从相对新的用户那里得到一个好的答案。向你们两个致敬。 - IRTFM
1个回答

21

为了根据输入的字符长度获得不同类型的输出,可以执行以下操作:

1)创建动态输出 uiOutput

2)在反应式环境 renderUI中根据输入选择输出类型。

3)渲染输出。

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

```

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接