Repository: joshkatz/r-script Branch: master Commit: 9b87a435b360 Files: 10 Total size: 12.5 KB Directory structure: gitextract_usb6pwvh/ ├── LICENSE ├── R/ │ └── launch.R ├── README.md ├── example/ │ ├── attitude.json │ ├── ex-async.R │ ├── ex-sync.R │ └── ex.js ├── index.js ├── needs.R └── package.json ================================================ FILE CONTENTS ================================================ ================================================ FILE: LICENSE ================================================ The MIT License (MIT) Copyright (c) 2015 Josh Katz Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: R/launch.R ================================================ source(file.path(Sys.getenv("DIRNAME"), "needs.R")) needs(jsonlite) run <- function(dataIn) { # set up environment input <- unname(dataIn[[1]]) .e <- as.environment(list( path = dataIn[[2]], out = modifyList(list(x = NULL, auto_unbox = T), dataIn[[3]], keep.null = T) )) lockBinding(".e", environment()) # run source, capture output captured <- tryCatch(capture.output({ temp <- source(.e$path, local = T)$value }), error = function(err) err) unlockBinding(".e", environment()) # process and return if (inherits(captured, "error")) { msg <- conditionMessage(captured) cat("Error in R script", .e$path, "\n", sQuote(msg), file = stderr()) return(invisible(F)) } .e$out$x <- if (is.null(temp)) { "" } else { temp } do.call(toJSON, .e$out) } suppressWarnings( run(fromJSON(Sys.getenv("input"))) ) ================================================ FILE: README.md ================================================ # r-script A simple little module for passing data from NodeJS to R (and back again). Data passed from node is converted into a list and loaded into the R environment as the variable `input`. No special syntax in R is needed. For better portability/reliability, it's recommended to load packages with [`needs`](https://github.com/joshkatz/needs) (comes packaged inside the module — no installation required). ### Installation ``` npm install r-script ``` ### Example ```js var R = require("r-script"); ``` ##### Synchronous ```javascript // example.js var out = R("ex-sync.R") .data("hello world", 20) .callSync(); console.log(out); // [ 'oedorlwlh l', 'oldlrhelwo ', 'erllol dhow', ' lwrellodoh', 'holdlerw ol', // 'lrlewdhol o', 'lll wohdeor', 'hwrlledl oo', 'elrooh lwld', 'ewrlo lhdlo', // 'hlloroelwd', 'h eodollwlr', 'wr ldleohlo', 'or ohldlwel', 'lohe lowlrd', // 'rhdwoelllo ', 'owhorldell ', 'rlle ohdolw', 'rhlwolle od', 'woro helldl' ] ``` ```r # ex-sync.R needs(magrittr) set.seed(512) do.call(rep, input) %>% strsplit(NULL) %>% sapply(sample) %>% apply(2, paste, collapse = "") ``` ##### Asynchronous ```javascript // example.js var attitude = JSON.parse( require("fs").readFileSync("example/attitude.json", "utf8")); R("example/ex-async.R") .data({df: attitude, nGroups: 3, fxn: "mean" }) .call(function(err, d) { if (err) throw err; console.log(d); }); // [ { group: '(40,55]', rating: 46.7143, advance: 41.1429 }, // { group: '(55,70]', rating: 64.6154, advance: 41.9231 }, // { group: '(70,85]', rating: 77.2, advance: 45.5 } ] ``` ```r # ex-async.R needs(dplyr) attach(input[[1]]) return("early returns are ignored") cat("so are undirected calls to cat") print("or print") cat("unless directed to a file", file = "out.Rout") # output of final expression is returned to node df %>% mutate(group = cut(rating, nGroups, ordered = T)) %>% group_by(group) %>% summarize_each(funs_(fxn)) %>% select(group, rating, advance) %>% mutate(group = as.character(group)) ``` ### Syntax **R**(_path_) Creates a new object that will source the R script specified by _path_. R.**data**(...) Adds data to the object and returns itself. You can give any number of arguments of different types. R.**call**([_options_], _callback_) Calls R. Any previously supplied _data_ is stringified into JSON and passed to R, where it's converted into a list and loaded into the R environment as the variable `input`. On completion, the _callback_ is invoked with two arguments: any error and the output from R, parsed back into a Javascript object. Additional arguments for the conversion from R to JSON can be specified as _options_ (see documentation for [```toJSON```](https://github.com/jeroenooms/jsonlite/blob/master/R/toJSON.R) from the R package `jsonlite` for defaults). R.**callSync**([_options_]) The same as above, but calls R synchronously. ================================================ FILE: example/attitude.json ================================================ [{"rating":43,"complaints":51,"privileges":30,"learning":39,"raises":61,"critical":92,"advance":45},{"rating":63,"complaints":64,"privileges":51,"learning":54,"raises":63,"critical":73,"advance":47},{"rating":71,"complaints":70,"privileges":68,"learning":69,"raises":76,"critical":86,"advance":48},{"rating":61,"complaints":63,"privileges":45,"learning":47,"raises":54,"critical":84,"advance":35},{"rating":81,"complaints":78,"privileges":56,"learning":66,"raises":71,"critical":83,"advance":47},{"rating":43,"complaints":55,"privileges":49,"learning":44,"raises":54,"critical":49,"advance":34},{"rating":58,"complaints":67,"privileges":42,"learning":56,"raises":66,"critical":68,"advance":35},{"rating":71,"complaints":75,"privileges":50,"learning":55,"raises":70,"critical":66,"advance":41},{"rating":72,"complaints":82,"privileges":72,"learning":67,"raises":71,"critical":83,"advance":31},{"rating":67,"complaints":61,"privileges":45,"learning":47,"raises":62,"critical":80,"advance":41},{"rating":64,"complaints":53,"privileges":53,"learning":58,"raises":58,"critical":67,"advance":34},{"rating":67,"complaints":60,"privileges":47,"learning":39,"raises":59,"critical":74,"advance":41},{"rating":69,"complaints":62,"privileges":57,"learning":42,"raises":55,"critical":63,"advance":25},{"rating":68,"complaints":83,"privileges":83,"learning":45,"raises":59,"critical":77,"advance":35},{"rating":77,"complaints":77,"privileges":54,"learning":72,"raises":79,"critical":77,"advance":46},{"rating":81,"complaints":90,"privileges":50,"learning":72,"raises":60,"critical":54,"advance":36},{"rating":74,"complaints":85,"privileges":64,"learning":69,"raises":79,"critical":79,"advance":63},{"rating":65,"complaints":60,"privileges":65,"learning":75,"raises":55,"critical":80,"advance":60},{"rating":65,"complaints":70,"privileges":46,"learning":57,"raises":75,"critical":85,"advance":46},{"rating":50,"complaints":58,"privileges":68,"learning":54,"raises":64,"critical":78,"advance":52},{"rating":50,"complaints":40,"privileges":33,"learning":34,"raises":43,"critical":64,"advance":33},{"rating":64,"complaints":61,"privileges":52,"learning":62,"raises":66,"critical":80,"advance":41},{"rating":53,"complaints":66,"privileges":52,"learning":50,"raises":63,"critical":80,"advance":37},{"rating":40,"complaints":37,"privileges":42,"learning":58,"raises":50,"critical":57,"advance":49},{"rating":63,"complaints":54,"privileges":42,"learning":48,"raises":66,"critical":75,"advance":33},{"rating":66,"complaints":77,"privileges":66,"learning":63,"raises":88,"critical":76,"advance":72},{"rating":78,"complaints":75,"privileges":58,"learning":74,"raises":80,"critical":78,"advance":49},{"rating":48,"complaints":57,"privileges":44,"learning":45,"raises":51,"critical":83,"advance":38},{"rating":85,"complaints":85,"privileges":71,"learning":71,"raises":77,"critical":74,"advance":55},{"rating":82,"complaints":82,"privileges":39,"learning":59,"raises":64,"critical":78,"advance":39}] ================================================ FILE: example/ex-async.R ================================================ # ex-async.R needs(dplyr) attach(input[[1]]) return("early returns are ignored") cat("so are undirected calls to cat") print("or print") cat("unless directed to a file", file = "out.Rout") # output of final expression is returned to parent df %>% mutate(group = cut(rating, nGroups, ordered = T)) %>% group_by(group) %>% summarize_all(funs_(fxn)) %>% select(group, rating, advance) %>% mutate(group = as.character(group)) ================================================ FILE: example/ex-sync.R ================================================ # example/ex-sync.R needs(magrittr) set.seed(512) do.call(rep, input) %>% strsplit(NULL) %>% sapply(sample) %>% apply(2, paste, collapse = "") ================================================ FILE: example/ex.js ================================================ #!/usr/bin/env node var R = require("r-script"); // sync var out = R("example/ex-sync.R") .data("hello world", 20) .callSync(); console.log(out); // async var attitude = JSON.parse( require("fs").readFileSync("example/attitude.json", "utf8")); R("example/ex-async.R") .data({df: attitude, nGroups: 3, fxn: "mean" }) .call(function(err, d) { if (err) throw err; console.log(d); }); ================================================ FILE: index.js ================================================ var _ = require("underscore"), child_process = require("child_process"); function init(path) { var obj = new R(path); _.bindAll(obj, "data", "call", "callSync"); return obj; } function R(path) { this.d = {}; this.path = path; this.options = { env: _.extend({DIRNAME: __dirname}, process.env), encoding: "utf8" }; this.idCounter = 0; this.args = ["--vanilla", __dirname + "/R/launch.R"]; } R.prototype.data = function() { for (var i = 0; i < arguments.length; i++) { this.d[++this.idCounter] = arguments[i]; } return this; }; R.prototype.call = function(_opts, _callback) { var callback = _callback || _opts; var opts = _.isFunction(_opts) ? {} : _opts; this.options.env.input = JSON.stringify([this.d, this.path, opts]); var child = child_process.spawn("Rscript", this.args, this.options); var body = ""; child.stderr.on("data", callback); child.stdout.on("data", function(d) { body += d; }); child.on("close", function(code) { callback(null, JSON.parse(body)); }); }; R.prototype.callSync = function(_opts) { var opts = _opts || {}; this.options.env.input = JSON.stringify([this.d, this.path, opts]); var child = child_process.spawnSync("Rscript", this.args, this.options); if (child.stderr) throw child.stderr; return(JSON.parse(child.stdout)); }; module.exports = init; ================================================ FILE: needs.R ================================================ tryCatch(needs(), error = function(e) { while (".needs" %in% search()) detach(.needs) .needs <- new.env(parent = .GlobalEnv) .needs$needs <- function(...) { needs_ <- function(...) { pkgs <- unlist(...) if (length(pkgs)) { loaded <- suppressMessages(suppressWarnings(sapply(pkgs, library, character = T, logical = T))) if (any(!loaded)) { missing <- pkgs[!loaded] cat("installing packages:n") cat(missing, sep = "n") utils::install.packages(missing, repos = "http://cran.rstudio.com/", quiet = T) } suppressMessages(suppressWarnings(sapply(pkgs, library, character = T))) } } packageInfo <- utils::installed.packages() if (missing(...)) return(invisible()) pkgs <- match.call()[-1] parsed <- if (is.null(names(pkgs))) { as.character(pkgs) } else { mapply(paste, names(pkgs), as.character(pkgs), MoreArgs = list(sep = ":")) } parts <- lapply(strsplit(parsed, "[:=(, ]+"), function(d) { d[d != ""] }) grouped <- split(parts, sapply(parts, length)) needs_(grouped$`1`) toCheck <- grouped$`2` if (length(toCheck)) { installedPackages <- packageInfo[, "Package"] needsPackage <- sapply(toCheck, `[`, 1) needsVersion <- sapply(toCheck, function(x) { gsub("[^0-9.-]+", "", x[2]) }) installed <- needsPackage %in% installedPackages needs_(needsPackage[!installed]) compared <- mapply(utils::compareVersion, needsVersion[installed], packageInfo[needsPackage[installed], "Version"]) if (any(compared == 1)) { toUpdate <- needsPackage[installed][compared == 1] cat("updating packages:n") cat(toUpdate, sep = "n") utils::update.packages(oldPkgs = toUpdate, ask = F) } needs_(needsPackage[installed]) } invisible() } # attach to the search path attach(.needs) }) ================================================ FILE: package.json ================================================ { "name": "r-script", "version": "0.0.4", "description": "A simple little module for passing data from NodeJS to R (and back again).", "keywords": [ "R", "rstats", "statistics" ], "homepage": "http://github.com/joshkatz/r-script", "bugs": "http://github.com/joshkatz/r-script/issues", "license": "MIT", "author": { "name": "Josh Katz" }, "main": "index.js", "repository": "joshkatz/r-script", "dependencies": { "underscore": "^1.8.3" }, "devDependencies": { "queue-async": "^1.0.7" } }