What command converts knitr R Markdown into Stack-Exchange-friendly Markdown?

前端 未结 3 1853
[愿得一人]
[愿得一人] 2020-12-30 04:20

Motivation: I often want to paste the results of a quick analysis using R Markdown into a StackExchange site. This includes the R-tag on Stack Overflow, Cro

相关标签:
3条回答
  • 2020-12-30 04:35

    Although I'd still like to read other suggestions I hacked together this script using @Ramnath's answer as a starting point. It outputs a HTML fragment rather than Markdown.

    Rscript -e 'rmd_file <- dir(pattern="rmd"); md_file <- sub("rmd", "md", rmd_file); html_file <- sub("rmd", "html", rmd_file); require(methods); require(knitr); require(markdown); opts_knit$set(upload.fun = imgur_upload); knit(rmd_file); markdownToHTML(md_file, html_file, options="fragment_only") '
    
    • It assumes that there is a single rmd file in the working directory. I imagine that selecting the rmd file could be done in a more sophisticated way.
    • It requires that the knitr and markdown packages are installed.
    • I think because we are using 'Rscript' the methods package needs to be loaded.
    • It uploads images to imgur
    • markdownToHTML exports only the code fragment as a html file. The contents of this file can then be copied into the Stack Exchange answer.

    The result looks pretty good. It overcomes the issue of excessive blank lines. However, the output is not markdown, which makes the result harder to edit.

    0 讨论(0)
  • 2020-12-30 04:37

    RStudio uses pandoc and so you can specify the markdown variant suitable for your needs. At the start of the .Rmd file:

    ---
    output:
      md_document:
        variant: markdown_strict+autolink_bare_uris
    ---
    

    You should then be able to copy/paste the resulting file contents into StackExchange.

    See: http://rmarkdown.rstudio.com/markdown_document_format.html#markdown-variants

    0 讨论(0)
  • 2020-12-30 04:46

    Here is a utility function that should get you started. It sets auto uploads to imgur, as well as markdown rendering of source code using tabs instead of fenced blocks. You can enhance this function to add other options that would be useful.

    stackify <- function(rmd_file, ...){
      require(knitr)
      opts_knit$set(upload.fun = imgur_upload) 
      render_markdown(strict = TRUE)
      out <- knit(rmd_file, ...)
      return(invisible(out))
    }
    

    UPDATE: I tested this function on your test file, and it renders well on stats.stackexchange.com which is mathjax enabled.

    0 讨论(0)
提交回复
热议问题