Include HTML files in R Markdown file?

36,446

Solution 1

Here is a hack (probably inelegant)...idea is to directly insert HTML programmatically in Rmd and then render Rmd.

temp.Rmd file:

---
title: "Introduction"
author: "chinsoon12"
date: "April 10, 2016"
output: html_document
---

<<insertHTML:[test.html]

etc, etc, etc

```{r, echo=FALSE}
htmltools::includeHTML("test.html")
```

etc, etc, etc

test.html file:

<html>

    <head>
    <title>Title</title>
    </head>

    <body>

        <p>This is an R HTML document. When you click the <b>Knit HTML</b> button a web page will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:</p>

        <p>test test</p>

    </body>
</html>

verbose code to replace Rmd code with HTML code and then render (can probably be shortened by a lot)

library(stringi)
subHtmlRender <- function(mdfile, htmlfile) {
    #replace <<insertHTML:htmlfile with actual html code
    #but without beginning white space
    lines <- readLines(mdfile)
    toSubcode <- paste0("<<insertHTML:[",htmlfile,"]")
    location <- which(stri_detect_fixed(lines, toSubcode) )
    htmllines <- stri_trim(readLines(htmlfile))

    #render html doc
    newRmdfile <- tempfile("temp", getwd(), ".Rmd")
    newlines <- c(lines[1:(location-1)],
                  htmllines,
                  lines[min(location+1, length(lines)):length(lines)])  #be careful when insertHTML being last line in .Rmd file
    write(newlines, newRmdfile)
    rmarkdown::render(newRmdfile, "html_document")
    shell(gsub(".Rmd",".html",basename(newRmdfile),fixed=T))
} #end subHtmlRender

subHtmlRender("temp.Rmd", "test.html")

EDIT: htmltools::includeHTML also works with the sample files that I provided. Is it because your particular html does not like UTF8-encoding?


EDIT: taking @MikeWilliamson comments into feedback

I tried the following

  1. copied and pasted animated_choropleth.html into a blank .Rmd
  2. remove references to cloudfare.com as I had access issues while rendering (see below)
  3. knit HTML
  4. put back those cloudfare weblinks
  5. put the graphs in the same folder as the rendered html
  6. open the HTML

I appear to get back the html but am not sure if the result is what you expect

Are you also facing the same issue in pt 2? You might want to post the error message and ask for fixes :). This was my error message

pandoc.exe: Failed to retrieve http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.1.1/css/bootstrap.min.css
FailedConnectionException2 "cdnjs.cloudflare.com" 80 False getAddrInfo: does not exist (error 11001)
Error: pandoc document conversion failed with error 61

Solution 2

Did you try the includes: option in your YAML header?

https://rmarkdown.rstudio.com/html_document_format.html#includes

But maybe you'll have the same problem I have: I'd like to include the HTML file in a specific section in my RMarkdown document, not in the header or before/after body.

Share:
36,446
Mike Williamson
Author by

Mike Williamson

Slowly moving away from doing the fun technical work. :(

Updated on February 15, 2020

Comments

  • Mike Williamson
    Mike Williamson over 4 years

    Quick Summary

    How do I place HTML files in place within an R Markdown file?

    Details

    I have created some nice animated choropleth maps via choroplethr.

    As the link demonstrates, the animated choropleths function via creating a set of PNG images, which are then rolled into an HTML file that cycles through the images, to show the animation. Works great, looks great.

    But now I want to embed / incorporate these pages within the .Rmd file, so that I have a holistic report including these animated choropleths, along with other work.

    It seems to me there should be an easy way to do an equivalent to

    Links:

    [please click here](http://this.is.where.you.will.go.html)
    

    or

    Images:

    ![cute cat image](http://because.that.is.what.we.need...another.cat.image.html)
    

    The images path is precisely what I want: a reference that is "blown up" to put the information in place, instead of just as a link. How can I do this with a full HTML file instead of just an image? Is there any way?

    Explanation via Example

    Let's say my choropleth HTML file lives in my local path at './animations/demographics.html', and I have an R Markdown file like:

    ---
    title: 'Looking at the demographics issue'
    author: "Mike"
    date: "April 9th, 2016"
    output:
      html_document:
        number_sections: no
        toc: yes
        toc_depth: 2
    fontsize: 12pt
    ---
    
    # Introduction
    
    Here is some interesting stuff that I want to talk about.  But first, let's review those earlier demographic maps we'd seen.
    
    !![demographics map]('./animations/demographics.html')
    

    where I have assumed / pretended that !! is the antecedent that will do precisely what I want: allow me to embed that HTML file in-line with the rest of the report.

    Updates

    Two updates. Most recently, I still could not get things to work, so I pushed it all up to a GitHub repository, in case anyone is willing to help me sort out the problem. Further details can be found at that repo's Readme file.

    It seems that being able to embed HTML into an R Markdown file would be incredibly useful, so I keep trying to sort it out.


    (Older comments)

    As per some of the helpful suggestions, I tried and failed the following in the R Markdown file:

    Shiny method:

    ```{r showChoro1}
    shiny::includeHTML("./animations/demographics.html")
    ```
    

    (I also added runtime:Shiny up in the YAML portion.)

    htmltools method:

    ```{r showChoro1}
    htmltools::includeHTML("./animations/demographics.html")
    ```
    

    (In this case, I made no changes to the YAML.)

    In the former case (Shiny), it did not work at all. In fact, including the HTML seemed to muck up the functionality of the document altogether, such that the runtime seemed perpetually not-fully-functional. (In short, while it appeared to load everything, the "loading" spindel never went away.)

    In the latter case, nothing else got messed up, but it was a broken image. Strangely, there was a "choropleth player" ribbon at the top of the document which would work, it's just that none of the images would pop up.


    For my own sanity, I also provided simple links, which worked fine.

    [This link](./animations/demographics.html) worked without a problem, except that it is not embedded, as I would prefer.
    

    So it is clearly a challenge with the embedding.

  • Mike Williamson
    Mike Williamson about 8 years
    Hi @chinsoon12 , this definitely seems like it should work, but I still did not have any luck. The code is actually not secret in any way, so I pushed it all to a GitHub repository. It'd be awesome if you could check the link to the repository that I'd made above. Otherwise, thanks so much for your help so far!
  • Mike Williamson
    Mike Williamson about 8 years
    Hi @chinsoon12 , thanks for the follow-up! I know that error, it's from trouble with bootstrap, a means of making more flexible HTML "shapes" (allowing for larger or smaller screens). I see you're right that I simply need to adjust the generated choroplethr HTML file itself. I didn't think of that being the issue. Once I figure it out well, I'll follow up with the choroplethr library folks. Thanks again!
  • chinsoon12
    chinsoon12 about 8 years
    No problem! Would be helpful to everyone to describe the error and fix in a edit :)
  • RLesur
    RLesur over 6 years
    Have you try to include HTML file in a <iframe> element?
  • chinsoon12
    chinsoon12 over 6 years
    @romles I have not tried it before. Are you facing difficulties? You can ask a question if you are facing 1.
  • Mike Williamson
    Mike Williamson over 6 years
    Sorry, I think you're misunderstanding what I am wanting to do. I am not asking how to render HTML or Shiny. I am asking how to place entire HTML files/pages within the R markdown document. I could cut & paste the HTML syntax in the file, but that is not very elegant, and the HTML file itself is a pre-generated, overly large garble, much like how generated HTML from R Markdown looks.
  • Mike Williamson
    Mike Williamson over 6 years
    Thanks @thbtmntgn ! That's a decent partial solution, but as you said, I wanted the HTML embedded/integrated into the document, not just either before or after the body. So it doesn't (fully) work for my case.
  • Rγσ ξηg Lιαη Ημ
    Rγσ ξηg Lιαη Ημ about 3 years
    <<insertHTML:[test.html] do not support mathjax but htmltools::includeHTML("test.html") support it, but how to adjust the size?