Last active
February 29, 2016 12:36
-
-
Save stla/bdace4f6929f83cf81d0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ```{r} | |
| library(knitr) | |
| knit_engines$set(V8 = runr:::V8engine) | |
| ``` | |
| By default the Javascript context is a R variable named `.context`. You can set another name by doing `opts_chunk$set(V8.context=mycontext)`. For instance: | |
| ```{r} | |
| library(V8) | |
| ct <- new_context() | |
| opts_chunk$set(V8.context=ct) | |
| ``` | |
| For example, we write the Javascript code below in a chunk with the option `engine='V8'`: | |
| ``` | |
| var x=[] | |
| for(i = 0; i<3; i++){ | |
| x[i]=i; | |
| } | |
| x.push([3,4]) | |
| JSON.stringify(x) | |
| ``` | |
| See it in action: | |
| ```{r, engine='V8'} | |
| var x=[] | |
| for(i = 0; i<3; i++){ | |
| x[i]=i; | |
| } | |
| x.push([3,4]) | |
| JSON.stringify(x) | |
| ``` | |
| In the previous chunk, the `results` option is set to its default value. You can use `results='hide'` to hide the output, or `results='last'` to show only the output generated by the last line: | |
| ```{r, engine='V8', results='last'} | |
| // this chunk has the options engine='V8' and results='last' | |
| var x=[] | |
| x.push([1,2]) | |
| x.push([3,4]) | |
| JSON.stringify(x) | |
| ``` | |
| Using the context variable you can import a variable from the Javascript context to R or vice-versa (see `?V8::V8` for details) : | |
| - Get `x` in R : | |
| ```{r} | |
| ( x.in.R <- ct$get("x") ) | |
| ``` | |
| - Double `x` in R and assign in Javascript context : | |
| ```{r} | |
| ct$assign("double_x", 2*x.in.R) | |
| ``` | |
| The Javascript function `JSON.stringify` is nice for displaying an object in a V8 chunk: | |
| ```{r, engine='V8'} | |
| // this chunk has the option engine='V8' | |
| JSON.stringify(double_x); | |
| ``` | |
| You can load a Javascript library as follows: | |
| ```{r} | |
| ct$source(system.file("js/underscore.js", package="V8")) | |
| ``` | |
| As you can see, it works: | |
| ```{r, engine='V8'} | |
| // this chunk has the option engine='V8' | |
| JSON.stringify(_.flatten(x)) | |
| ``` | |
| Another way is to give the libraries as a character vector in the `V8.libraries` chunk option: | |
| ```{r, eval=FALSE} | |
| opts_chunk$set(V8.libraries=c(system.file("js/underscore.js", package="V8"), "http://coffeescript.org/extras/coffee-script.js")) | |
| ``` | |
| The libraries given by this way are loaded only once, at the moment the Javascript context is created. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment