H Khan
H Khan

Reputation: 1347

Is there a way to run R code from JavaScript?

I am working on a project which requires some R code to be run for some data analysis. The project is primarily in JavaScript, and I need a way to run R code from JS. My research has not found any good way to do it yet. Is there any way to do so?

Also, I have next to no experience with R (another person is supplying the R code).

Upvotes: 54

Views: 52163

Answers (4)

Brandmaier
Brandmaier

Reputation: 134

I am answering ten years after the question was posed initially and web technology has advanced drastically. I suggest that WebR is a solution to the problem. WebR is a version of the statistical language R compiled for the browser. Using latest technologies for deployment of code to browsers (Node.js and WebAssembly), it is now possible to have R run in your browser (including many CRAN packages).

This allows you to run native R code in the browser without any installation, such as:

fit <- lm(mpg ~ am, data=mtcars)
summary(fit)

At the time of writing, there is active development happening on https://github.com/r-wasm/webr/.

Upvotes: 0

Tom Panning
Tom Panning

Reputation: 4772

If you're ok with having the R code run on a server, then you should take a look at OpenCPU. It provides a REST API and corresponding JavaScript library for sending R code to the server and getting the results back. In particular, it takes care of the security problems that can arise from running R as a server (R code can run arbitrary shell commands, among other things). There are public demo instances that you can use to try it out, and this page provides a simple tutorial.

Upvotes: 25

ngopal
ngopal

Reputation: 93

This is by no means the best way, but I was able to do the following for my own Javascript+R project (silly.r is an R script that lives in the "r" directory). I basically ran the R code as a terminal command from my express server:

app.get('/sfunction', function (req, res) {
    exec('Rscript r/silly.r this is a test', function(error, stdout, stderr) {
        if (error) {
            console.log(error);
            res.send(error);
        }
        else if (stderr) {
            console.log(stderr);
            res.send(stderr);
        }
        else if (stdout) {
            console.log("RAN SUCCESSFULLY");
            res.sendfile("savedoutput/test.json");
        }
    });
});

The code is from lines 167-182 from here: https://github.com/ngopal/VisualEncodingEngine/blob/master/jsserver/app.js

Upvotes: 2

user2578094
user2578094

Reputation:

How about R-node ?

I think another alterative would be to use node.js as a server (http://nodejs.org/) and call R from within as a child process, search the Node.js API docs for specifics.

Also look at this for confirmation: Is it possible to execute an external program from within node.js?

Note: node can run any JS script(s) you may have, they don't necessarily need to be node-specific.

Upvotes: 13

Related Questions