Ching-Chuan Chen's Blogger

Statistics, Machine Learning and Programming

0%

R call javascript

今天看到javascript call R似乎很容易

就稍微看一下R call javascript的方法

然後就看到V8這個套件,玩了一下覺得很驚豔XD

感覺javascript很適合拿來做一些R不容易做的功能XDD

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
library(V8)
ctx <- v8()
ctx$source("http://underscorejs.org/underscore-min.js")
ctx$eval("var list = [[0, 1], [2, 3], [4, 5]];")
ctx$eval("var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []);")
ctx$get("flat")
# [1] 4 5 2 3 0 1

ctx$assign("x", 1:5)
ctx$eval("var y = _.each(x, function(x){ return x*3;})")
ctx$get("y")
# [1] 1 2 3 4 5

x2 <- 1:5
ctx$call("_.each", x2, JS("function(x){ return x*3;}"))
# [1] 1 2 3 4 5


ctx$call("_.filter", mtcars, JS("function(x){return x.mpg < 15}"))
# mpg cyl disp hp drat wt qsec vs am gear carb
# Duster 360 14.3 8 360 245 3.21 3.570 15.84 0 0 3 4
# Cadillac Fleetwood 10.4 8 472 205 2.93 5.250 17.98 0 0 3 4
# Lincoln Continental 10.4 8 460 215 3.00 5.424 17.82 0 0 3 4
# Chrysler Imperial 14.7 8 440 230 3.23 5.345 17.42 0 0 3 4
# Camaro Z28 13.3 8 350 245 3.73 3.840 15.41 0 0 3 4

# work with npm
Sys.setenv(PATH = paste0(Sys.getenv("PATH"), ";C:\\Program Files\\nodejs;C:\\Users\\Jamal\\AppData\\Roaming\\npm"))
Sys.setenv(NODE_PATH = "C:\\Program Files\\nodejs\\node_modules;C:\\Users\\Jamal\\AppData\\Roaming\\npm\\node_modules")
system("npm install -g browserify js-beautify")
writeLines("global.beautify = require('js-beautify');", "in.js")
system("browserify in.js -o bundle.js")

ct <- v8()
ct$source("bundle.js")
test <- "(function(x,y){x = x || 1; y = y || 1; return y * x;})(4, 9)"
pretty_test <- ct$call("pr.js_beautify", test, list(indent_size = 2))
cat(pretty_test)
# (function(x, y) {
# x = x || 1;
# y = y || 1;
# return y * x;
# })(4, 9)