英文:
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
> x <- if(2==3) {print(4)}
> 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).
> x <- if(2==3) {print(4)}
> x
NULL
Is it clear?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论