conditional plotting not working as expected in a shiny document

huangapple go评论81阅读模式
英文:

conditional plotting not working as expected in a shiny document

问题

我想制作闪亮文档,读者可以在不同版本的图表/表格之间进行选择。

第一个示例运行正常,但只有在选择选项二时,第二个示例才能运行。唯一的区别是if{}else{}if{}if{}结构。

希望用户能够选择几个图表,而不仅仅是一个或两个。

英文:

I would like to make shiny documents in which the reader can choose between different versions of a graphs/table.

The first example works fine, but the second example only works if option two is selected. Only difference is if{}else{} vs if{}if{} structure.

would like for the user to choose a few graphs rather than just one or two.

---
output: html_document
runtime: shiny
---


#```{r eruptions, echo=FALSE}
inputPanel(
  selectInput("option",
    label = "Number of bins:",
    choices = c(1, 2, 3), selected = 1
  ),
)

renderUI({
  if (input$option == 1) {
    renderPlot({
      plot(1:10)
    })
  } else {
    renderPlot({
      plot(1:10, 10:1)
    })
  }
})
#```

#```{r eruptions2, echo=FALSE}
inputPanel(
  selectInput("option2",
    label = "Number of bins:",
    choices = c(1, 2, 3), selected = 1
  ),
)

renderUI({
  if (input$option2 == 1) {
    renderPlot({
      plot(1:10)
    })
  }
  if (input$option2 == 2) {
    renderPlot({
      plot(1:10, 10:1)
    })
  }
})


</details>


# 答案1
**得分**: 1

```r
R执行花括号内表达式的最后一条语句。如果 `input$option2 == 1`,它继续阅读代码,这是带有 `if(input$option == 2)` 的代码。由于这个条件未实现,输出为 `NULL`(不可见)。

```r
&gt; x &lt;- if(2==3) {print(4)}
&gt; x
NULL

清楚吗?


<details>
<summary>英文:</summary>

```r
renderUI({
  if (input$option2 == 1) {
    renderPlot({
      plot(1:10)
    })
  }
  if (input$option2 == 2) {
    renderPlot({
      plot(1:10, 10:1)
    })
  }
})

R executes the last statement of the expression between the curly braces. If input$option2 == 1, it continues to read the code, the one with if(input$option == 2). Since this condition is not realized, the output is NULL (invisibly).

&gt; x &lt;- if(2==3) {print(4)}
&gt; x
NULL

Is it clear?

huangapple
  • 本文由 发表于 2023年5月23日 00:04:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76308034.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定