Create gist from RMarkdown code chunk


#1

Posted this on Twitter and Maëlle Salmon asked me to post here. I’m trying to come up with a solution to have RMarkdown code chunks automatically generate gists. I’m creating an online course and I want to embed answers to problems on the website. The ideal way to do this would be to have code chunks in a solutions.Rmd file generate gists that I could then embed.

Maëlle pointed me to the gistr package, but I’m not clear whether it can do this. Any guidance would be appreciated!


#2

Thanks for posting here! :wave:

So the R Markdown file would produce the solution and create gists every time you knit it, which might happen several times because of updates right?

Then you’d need something to know the gists ID on your website, right?

The gistr expert (/creator/maintainer) is @sckott.


#3

Yes, I think that’s exactly what I’m looking for.


#4

:thinking: Any idea @sckott?


listed #5

#6

Good question. I imagine there are a few ways to do this. Here’s one approach:

Given a .Rmd file like

    ---
    title: "gistr eg"
    author: "Jane Doe"
    date: "`r Sys.Date()`"
    ---

    ```{r echo=FALSE}
    knitr::opts_chunk$set(
      comment = "#>",
      collapse = TRUE,
      warning = FALSE,
      message = FALSE
    )
    ```

    ```{r eval=FALSE}
    head(mtcars)
    plot(mpg ~ disp, data = mtcars)
    ```

    ```{r echo=FALSE}
    res <- gistr::gist_create("example1.Rmd", 
      browse = FALSE, knit = TRUE, imgur_inject = TRUE)
    gistr::embed(res)
    ```

Where the contents of the example1.Rmd are

    ```{r}
    head(mtcars)
    plot(mpg ~ disp, data = mtcars)
    ```

Where e.g., the first example block can be shown to the reader and has the code they’d run. And then a 2nd block has code that creates a gist and then embeds the gist below.

gistr::gist_create can take a file or block of code. But when taking a block of code it quickly gets messy as you have to escape lots of things cause you need to run a knitr chunk inside of a Rmd document, so pretty messy.

The only part thats missing is ther’es probably a knitr chunk option I’m not getting right for embedding the gist <script> tag. an eg would be <script src="https://gist.github.com/sckott/bc83e1c4f1bb1c1f3f157a15c7b696a5.js"></script>


#7

Thanks. I think this should work. I’ll test it out and get back you with any other questions.