library(knitr)
split_results <- function (x, sep) # function borrowed from runr package
{
x = strsplit(paste(x, collapse = "\n"), sep)[[1]]
res = vector("list", length(x))
for (i in seq_along(x)) {
el = gsub("^\n+|\n+$", "", x[i])
res[[i]] = if (i%%2 == 1)
structure(list(src = el), class = "source")
else paste(el, collapse = "\n")
}
res
}
knit_engines$set(V8 = function(options) {
code <- as.character(c(options$code))
output <- ct$eval(code)
code <- lapply(split_results(code, sep="this_is_a_stupid_string"), function(x) knitr:::wrap.source(x, options))
if(options$results=="hide") return(code)
else return(c(code, knitr:::wrap.character(output, options)))
})
Load V8 and define a new context named ct:
library(V8)
ct <- new_context()
Define x in Javascript context using the chunk option engine='V8':
var x=[];
x.push([1,2]);
x.push([3,4]);
x.push([5,6]);
JSON.stringify(x)
## [[1,2],[3,4],[5,6]]
Get x in R :
( x.in.R <- ct$get("x") )
## [,1] [,2]
## [1,] 1 2
## [2,] 3 4
## [3,] 5 6
Double x in R and assign in Javascript context :
ct$assign("double_x", 2*x.in.R)
JSON.stringify(double_x);
## [[2,4],[6,8],[10,12]]
Load a Javascript library :
ct$source(system.file("js/underscore.js", package="V8"))
JSON.stringify(_.flatten(x))
## [1,2,3,4,5,6]