用于呈现函数的反应参数

Tyl*_*ker 3 r shiny flexdashboard

我在flexdashboard中有一个表,其列数可以更改.我可以动态计算列的对齐方式(默认对齐视为$23.45字符向量,因此左对齐值,尽管它是一个数字,应该右对齐).问题是我无法将此对齐renderTable作为值传递回,align因为它是一个无效值.

如何将反应对齐传递回renderTable函数的align参数?(或者让我渲染具有反应对齐的表格的替代方案)

MWE

---
title: "test"
output: flexdashboard::flex_dashboard
runtime: shiny
---

```{r}
library(flexdashboard)
library(shiny)
```

Inputs {.sidebar}
-------------------------------------

```{r}
selectInput(
    "ncols", 
    label = "How many columns?",
    choices = 1:5, 
    selected = 5
)
```  

Column  
-------------------------------------

### Test

```{r}
nc <- reactive({input$ncols})
aln <- reactive({substring('lllrr', 1, nc())})

renderTable({
    x <- CO2[1:5, seq_len(nc()), drop = FALSE]
    x[, 1] <- as.character(x[, 1])
    x[3, 1] <- '<b>Mc1</b>'
    x
}, align = aln(), sanitize.text.function = function(x) x)
```
Run Code Online (Sandbox Code Playgroud)

结果是:

 Warning: Error in .getReactiveEnvironment()$currentContext: Operation not 
 allowed without an active reactive context. (You tried to do something 
 that can only be done from inside a reactive expression or observer.)
Run Code Online (Sandbox Code Playgroud)

Wei*_*ong 7

尝试包裹aln()renderText(...)

renderTable({
    x <- CO2[1:5, seq_len(nc()), drop = FALSE]
    x[, 1] <- as.character(x[, 1])
    x[3, 1] <- '<b>Mc1</b>'
    x
}, align = renderText(aln()), 
   sanitize.text.function = function(x) x)
Run Code Online (Sandbox Code Playgroud)

  • 我只想添加 - **这只能起作用,因为`renderTable` [接受可以作为函数调用的参数](https://github.com/rstudio/shiny/blob/v1.0.5/R/render-table. R·L69-L80)**.它不适用于其他渲染函数.这也意味着既不需要`reactive`也不是`renderText`,你可以传入一个函数,比如`aln < - function()substring('lllrr',1,nc())`,`renderTable(... ,align = aln)` (2认同)

K. *_*hde 6

首先,发生的具体错误是非常正确的.该函数renderTable只能在其第一个参数中保存反应式表达式renderTable({ ... }, ...).所有其他东西必须是普通物体.因此,将反应值放在aln()那里真的是reactive在一个普通的环境中.或者,从reactive它自身的角度来看,它是在没有像错误消息中所述的活动反应上下文的情况下进行评估的.

使这些事物变得反应的一种解决方法是围绕它的包装renderTable,即renderUI.在renderUI我们内部,我们可以反应性地塑造整个表格渲染,其中包括对齐.(解决方案部分改编自此处.)

以下是您需要替换的内容renderTable:

renderUI({
  output$table <- renderTable({
      x <- CO2[1:5, seq_len(isolate(nc())), drop = FALSE]
      x[, 1] <- as.character(x[, 1])
      x[3, 1] <- '<b>Mc1</b>'
      x
  }, align = aln(), sanitize.text.function = function(x) x)

  tableOutput("table")
})
Run Code Online (Sandbox Code Playgroud)

快速解释:使用output变量就像在常规闪亮环境中一样,如果没有降价的话.renderUI然后将呈现的是对renderTable每次我们将从头开始重新创建的引用.

注意:我用过isolate里面的renderTable.原因如下:renderTable是反应性的,如果nc()发生变化会更新.但这可能发生在周围环境renderUI对变化作出反应之前.您会看到,在此中间步骤中,renderTable尝试绘制data.frame具有不同列数的a,但align仍然是之前的列数.抛出错误,因为它们不匹配.隔离内部会nc()阻止内部renderTable更新.但这没关系,因为renderUI一旦轮到它更新,外部就会这样做.