【问题标题】:How to display or hide R flexdashboard component based on shiny input value?如何根据闪亮的输入值显示或隐藏 R flexdashboard 组件?
【发布时间】:2021-10-15 09:56:04
【问题描述】:

我想根据 Shiny 输入值显示或隐藏 R flexdashboard 组件。为此,我正在尝试执行动态创建新的 3 级降价部分的代码。如果我运行以下代码,我将获得带有侧边栏和 3 个组件的预期文档 - 即,最终代码块创建“Section C”组件。

---
title: "Sample Flexdashboard"
output: 
  flexdashboard::flex_dashboard:
    orientation: columns
    vertical_layout: fill
runtime: shiny
---

```{r setup, include=FALSE}
library(flexdashboard)
```

## Sidebar {.sidebar}
```{r}
radioButtons(
  "select",
  "Show or hide component",
  choices = c("Show" = "show", "Hide" = "hide"),
  selected = "show"
)
```

## Column

### Section A

### Section B

```{r, results='asis'}
cat(paste0("\n",
           "### ",
           "Section C",
           "\n"))
```

但是,当我使用以下内容作为我的最后一个块来根据“选择”输入值显示/隐藏部分 C 时,它会将 ### Section C 文本打印为部分 B 中的代码,而不是使用它创建一个新组件文本作为降价。

```{r, results='asis'}
renderPrint(
  if (input$select == "show") {
    cat(paste0("\n",
               "### ",
               "Section C",
               "\n"))
    }
  )
```

也许有比 renderPrint 更好的函数?

【问题讨论】:

标签: r shiny flexdashboard


【解决方案1】:

我的包目前与这个带有 runtime:shiny 的 flexdashboard 不兼容。所以我无法测试这个解决方案,而是根据以前的经验。

cat() 返回一个文本字符串。这就是为什么它被原样解释为一个新的标题。

当您将if 语句放在一个部分中时,块返回最后一个运行的对象......这是if 语句而不是cat 语句。您可以通过在 if 语句完成后显式返回所需的对象来解决此问题。如果您不希望返回任何内容,您可以将文本设置为 NULL

```{r, results='asis'}
if (input$select == "show") {
  sec3text <- cat(paste0("\n",
             "### ",
             "Section C",
             "\n"))
  } else {
  sec3text <- NULL
}
sec3text
```

renderPrint() 返回一个函数,告诉 shiny 或 flexdashboard 在框中打印什么。因为它不是文本字符串“### Section 3”,所以 flex 仪表板将其解释为要呈现的对象。您可以通过将 renderPrint 的结果分配给测试变量然后查看结构来看到这一点。

> test <- shiny::renderPrint("Some print")
> str(test)
function (...)  
 - attr(*, "class")= chr [1:2] "shiny.render.function" "function"
 - attr(*, "outputFunc")=function (outputId, placeholder = FALSE)  
 - attr(*, "outputArgs")= list()
 - attr(*, "hasExecuted")=Classes 'Mutable', 'R6' <Mutable>
  Public:
    clone: function (deep = FALSE) 
    get: function () 
    set: function (value) 
  Private:
    value: FALSE 
 - attr(*, "cacheHint")=List of 2
  ..$ label       : chr "renderPrint"
  ..$ origUserExpr: chr "Some print"

因此,如果您希望 RMD 解释您的文本,您需要将其键入为 YAML 而不是函数。

【讨论】:

  • 感谢您的回复。您提供的代码块(使用“sec3text”)不太有效,因为 input$select 需要在 reactive() 中调用。您能否详细说明将文本键入为 YAML 而不是函数的样子?
猜你喜欢
  • 2021-09-08
  • 2020-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-15
  • 2016-03-10
  • 2018-10-30
  • 2022-01-18
相关资源
最近更新 更多