Rmarkdown html:在带有标题编号的自定义表中内联反应式闪亮内容

时间:2019-06-22 22:23:06

标签: html r shiny r-markdown knitr

我想在自定义格式的表格中显示大量的回归估计(现有的软件包,例如stargazer不会给出足够紧凑的结果)。我希望读者能够为要使用shiny小部件显示的估算值选择参数。对于大多数内容,这很容易,但是当内容必须在html标签内插入时,这似乎非常困难。我尝试过

  1. 在响应式函数的HTML()调用中创建整个表,然后在该函数上调用renderUI()
  2. 在html标签中包含反应性内容

除了标题标签和编号失败之外,我设法使表与第一种方法一起使用。我尝试将标签(#tab:TableLabel1)传递给knitr::knit2html(),但结果相同。我还尝试用等效的html替换shiny标记,这没有改变,并且使代码更长,因为我必须手动指定每个td而不是使用paste()向量。我在下面提供了一个工作示例(它使用dplyr)。

---
output: bookdown::html_document2
runtime: shiny
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(dplyr)
library(shiny)
```

<style>
  th + th {padding-left: 20px;}
  td + td {padding-left: 20px;}
  th + td {padding-left: 20px;}
</style>


```{r data}
dt = as_tibble(expand.grid(Sample=1:3, DepVar=1:3)) %>%
     mutate(Coef = round(rnorm(length(Sample)),2),
            SE = round(runif(length(Sample)),2))
```

```{r SampleChoice}
selectInput("Sample", label = "Choose a sample to view", choices=list(1,2,3), selected=1)
```

This table is great, but I cannot get the caption label to work properly:
```{r printtable}
PrintTable = eventReactive(input$Sample, {
  HTML(
    '<table>',
    '<caption>(#tab:TableLabel1) the first table</caption>',
    '<tr><th>Row group heading</th></tr>',
    '<tr><th>Variable</th>',
    paste0('<td>', dt$Coef[dt$Sample == as.numeric(input$Sample)],'</td>', collapse=""),
    '</tr>',
    '<tr><th></th>',
    paste0('<td>(', dt$SE[dt$Sample == as.numeric(input$Sample)],')</td>', collapse=""),
    '</tr>',
    '</table>'
  )
})
renderUI(print_table())
```

<br>
Moving everything except the reactive content outside of the HTML() call 
makes the caption work properly but causes all the reactive content 
to show up outside the table:

```{r PrintSE}
print_Coef = eventReactive(input$Sample, {
  HTML(paste0('<td>(', dt$Coef[dt$Sample == as.numeric(input$Sample)],')</td>', collapse=""))
})
print_SE = eventReactive(input$Sample, {
  HTML(paste0('<td>(', dt$SE[dt$Sample == as.numeric(input$Sample)],')</td>', collapse=""))
})
```

<table>
<caption>(#tab:TableLabel2) the second table</caption>
<tr><th>Row group heading</th></tr>
<tr><th>Variable</th>`r renderUI(print_Coef())`</tr>
<tr><th></th>`r renderUI(print_SE())`</tr>
</table>

0 个答案:

没有答案