Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
43 lines (31 sloc) 1.41 KB

Using CoffeeScript with knitr

First we set a flag -p for the coffee engine to print the JavaScript output instead of evaluating the code (engine.opts = '-p'):

knitr::opts_chunk$set(cache = TRUE, engine.opts = '-p')

You need to install coffee, the command-line version of CoffeeScript.

CoffeeScript compiles javascript:

@square = (x) -> x * x

To use CoffeeScript in an HTML document, use results="asis", echo=FALSE, and wrap the chunk in <script> tags.

<script type="text/javascript"> ```{r math_functions, engine="coffee", results="asis", echo=FALSE} @square = (x) -> x * x @cube = (x) -> square(x) * x ``` ```{r call_math, engine="coffee", results="asis", echo=FALSE} p = document.createElement("p"); p.appendChild(document.createTextNode("The cube of 3 is " + cube(3))) document.body.appendChild(p) ``` </script>

Of course you can also run the code, if you remove the -p flag from the chunk option engine.opts (I'm not evaluating this code chunk here because I do not have a proper version of coffee on Debian yet; if you do, you can remove eval=FALSE):

x = 42
console.log "The answer is ", x