conditional plotting not working as expected in a shiny document

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

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.

  1. ---
  2. output: html_document
  3. runtime: shiny
  4. ---
  5. #```{r eruptions, echo=FALSE}
  6. inputPanel(
  7. selectInput("option",
  8. label = "Number of bins:",
  9. choices = c(1, 2, 3), selected = 1
  10. ),
  11. )
  12. renderUI({
  13. if (input$option == 1) {
  14. renderPlot({
  15. plot(1:10)
  16. })
  17. } else {
  18. renderPlot({
  19. plot(1:10, 10:1)
  20. })
  21. }
  22. })
  23. #```
  24. #```{r eruptions2, echo=FALSE}
  25. inputPanel(
  26. selectInput("option2",
  27. label = "Number of bins:",
  28. choices = c(1, 2, 3), selected = 1
  29. ),
  30. )
  31. renderUI({
  32. if (input$option2 == 1) {
  33. renderPlot({
  34. plot(1:10)
  35. })
  36. }
  37. if (input$option2 == 2) {
  38. renderPlot({
  39. plot(1:10, 10:1)
  40. })
  41. }
  42. })
  43. </details>
  44. # 答案1
  45. **得分**: 1
  46. ```r
  47. R执行花括号内表达式的最后一条语句。如果 `input$option2 == 1`,它继续阅读代码,这是带有 `if(input$option == 2)` 的代码。由于这个条件未实现,输出为 `NULL`(不可见)。
  48. ```r
  49. &gt; x &lt;- if(2==3) {print(4)}
  50. &gt; x
  51. NULL

清楚吗?

  1. <details>
  2. <summary>英文:</summary>
  3. ```r
  4. renderUI({
  5. if (input$option2 == 1) {
  6. renderPlot({
  7. plot(1:10)
  8. })
  9. }
  10. if (input$option2 == 2) {
  11. renderPlot({
  12. plot(1:10, 10:1)
  13. })
  14. }
  15. })

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

  1. &gt; x &lt;- if(2==3) {print(4)}
  2. &gt; x
  3. 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:

确定