问题
我正在尝试在Shiny应用程序中呈现一个R Markdown文档,并使用David在这篇文章中非常有帮助的解决方案成功实现了目标(RMarkdown in Shiny Application)。然而,我无法从与Shiny应用程序和R Markdown文档放置在同一目录中的.bib文件中渲染带有引用的文档。请查看下面的最小可重现示例。
R Markdown文档
RMarkdownFile.rmd
---
title: "RMarkdownFile"
author: "Test Author"
date: "15/10/2020"
output: html_document
bibliography: bibliography.bib
link-citations: yes
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
# Statement
ggplot2 [@wickham2016ggplot2] is a great package!
## References
Bibliography
bibliography.bib
@book{wickham2016ggplot2,
title={ggplot2: elegant graphics for data analysis},
author={Wickham, Hadley},
year={2016},
publisher={springer}
}
闪亮应用
app.R
library(shiny)
library(knitr)
rmdfiles <- c("RMarkdownFile.rmd")
sapply(rmdfiles, knit, quiet = T)
ui <- shinyUI(
fluidPage(
withMathJax(includeMarkdown("RMarkdownFile.md"))
)
)
server <- function(input, output) { }
shinyApp(ui, server)
结果
在应用程序之外编织RMarkdownFile.rmd可以完美地工作,生成以下输出。
RMarkdownFile
Test Author
15/10/2020
Statement
ggplot2 (Wickham 2016) is a great package!
References
Wickham, Hadley. 2016. Ggplot2: Elegant Graphics for Data Analysis. springer.
然而,按照上述方法在Shiny应用程序中呈现RMarkdownFile.md会失败,并且无法从bibliography.bib文件中生成文档中的引文和参考文献,如下所示。
Statement
ggplot2 [@wickham2016ggplot2] is a great package!
References
更新 - 解决方案
经过尝试了几种不同的方法,最简单的方法最终起作用。以下是更新后的Shiny应用程序,其中包括从R markdown文档呈现的html文档,并带有引用。
app.R
library(shiny)
library(knitr)
rmarkdown::render("RMarkdownFile.Rmd")
ui <- shinyUI(
fluidPage(
includeHTML("RMarkdownFile.html")
)
)
server <- function(input, output) { }
shinyApp(ui, server)
额外的问题
然而......当在R markdown的YAML块中包含"self_contained: false"时,这仅适用于基本的HTML文档。
---
title: "RMarkdownFile"
author: "Test Author"
date: "15/10/2020"
output:
html_document:
self_contained: false
bibliography: bibliography.bib
link-citations: yes
---
结果会被放在一个补充文件夹中,名称为“RMarkdownFile_files”,这些内容将无法被Shiny应用程序找到。通过使用Rstudio devtools检查Shiny中缺失的元素,我们发现以下错误:
无法加载资源:服务器响应了404(未找到)状态
然而,如果在YAML块中包含“self_contained: true”,则这些元素将不再缺失,但我将无法访问我在非reprex Shiny应用程序中使用的多个选项卡。
编辑:我现在已经在另一篇文章包括了使用shinydashboard在R Shiny应用程序中渲染自RMarkdown的HTML文件导致tabItems出错的问题
正确的方法
编辑:使用下面的代码已经解决了这些问题,请注意,除非直接在那里呈现,否则RMarkdownFile.html文件必须放置在Shiny应用程序目录中的“www”文件夹中。
library(shiny)
library(knitr)
rmarkdown::render("RMarkdownFile.Rmd")
ui <- shinyUI(
fluidPage(
htmltools::tags$iframe(src = "RMarkdownFile.html", width = '100%', height = 1000, style = "border:none;"))
)
)
server <- function(input, output) { }
shinyApp(ui, server)
withMathJax(includeMarkdown("RMarkdownFile.md"))
? - HubertL