1

I found out from this question that you can call Knitr from a script like this:

Rscript -e "library(knitr); knit('myfile.Rmd')

But is there a way to get it to use stdin and stdout instead of files?

I tried several variations on

Rscript -e 'library(knitr); knit2html(text=readLines(), output=stdout())'

but none have worked so far.

EDIT: I suppose worst case, I could write a wrapper script that writes stdin to a temp file, calls knitr on it, echoes the output file, and deletes them. But that's kind of ugly :(

Community
  • 1
  • 1
jefdaj
  • 2,025
  • 2
  • 21
  • 33
  • See http://stackoverflow.com/questions/9370609/piping-stdin-to-r perhaps. – mnel Sep 19 '13 at 02:49
  • and be sure to use the argument `quiet=TRUE` in `knit()` or `knit2html()` to suppress other possible messages that may pollute `stdout()` – Yihui Xie Sep 19 '13 at 13:26

2 Answers2

1

OK I tried it again today, and here's a working script:

#!/bin/bash

# Hacky version of what I thought should be doable like so:
# Rscript -e 'library(knitr); knit2html(text=readLines(), output=stdout())'
# Turns out you need tempfiles for some reason?

input="/tmp/input.Rmd"
output="/tmp/output.html"
rcode="library(knitr); knit2html(input=\"$input\", output=\"$output\")"

cat /dev/stdin > "$input"
Rscript -e "$rcode" &> /dev/null
cat "$output"

You pipe R markdown in and HTML comes out. Ignores any errors.

jefdaj
  • 2,025
  • 2
  • 21
  • 33
0

Here is one version:

#!/bin/Rscript
library(knitr)
input <- readLines('stdin')
invisible(knit(text=input, output=stdout(), quiet=TRUE))

Then (assuming script is knit.R, rmd file is test.R and md to html converted is multimarkdown:

knit.R < test.Rmd | multimarkdown > test.html
Karolis Koncevičius
  • 9,417
  • 9
  • 56
  • 89