Monday, April 10, 2017

How to render table and math in Rmarkdown when called from Shiny App

Leave a Comment

I have a Rmarkdown file (info.rmd) that looks like this:

--- title: "Information" theme: yeti date: "4/1/2017" output: html_document ---   ## R Markdown  This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.   ```{r echo = FALSE, results = 'asis'} library(knitr) kable(mtcars[1:5, ], caption = "A knitr kable.") ```  ## Formulation  Here is where we formulate $$\sum_{i=1}^n X_i$$ 

And the ShinyApp that calls Rmarkdown like this:

server.R

contains this

  output$markdown <- renderUI({     HTML(markdown::markdownToHTML(knit('info.rmd', quiet = TRUE), fragment.only=TRUE))   }) 

ui.R

contains this:

 fluidPage(uiOutput('markdown')) 

But how come the table and math generated looks like this?

enter image description here

What's the right way to do it?


When run independently outside Shiny the info.rmd produces the table properly:

enter image description here


I tried this in ui.R

 includeHTML("info.html") 

Which shows the file html correctly, but prevent the plotting and reactivity in other tabPanel() to work.


Update

Here is the new result after @Nice solution:

enter image description here

2 Answers

Answers 1

If you use fragment.only, the CSS and JS is not included and the table/equation is not styled.

One easy way to do this is to include the full HTML, with the header, in an iframe so it does not interfere with the rest of your app.

output$markdown <- renderUI({     tags$iframe(src='info.html',width="100%",frameBorder="0",height="1000px")   }) 

The info.html file needs to be in the www folder of your app. You can adjust the width and height of the iframe by changing the parameters in the tags$iframe.

You can change the width of the main container in the iframe using CSS. If you add this to your info.rmd file:

```{r results="asis",echo = FALSE} cat(" <style> .main-container.container-fluid {    max-width: 100%;    padding-left:0px; } </style> ") ``` 

Answers 2

Editing the shiny server part with the following should help:

output$markdown <- renderUI({     markdown::markdownToHTML(knit('info.rmd', quiet = TRUE), fragment.only=TRUE)     withMathJax(includeHTML("info.html"))   }) 

Alternatively you can also do the following:

output$markdown <- renderUI({     markdown::markdownToHTML(knit('info.rmd', quiet = TRUE), fragment.only=TRUE)     withMathJax(includeMarkdown("info.md"))   }) 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment