Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to run R code from JavaScript?

Tags:

javascript

r

People also ask

Can you use R in JavaScript?

You're lucky, you can actually use JavaScript in R Markdown. At a basic level, knitr includes a JavaScript chunk engine that writes the code in JavaScript chunks marked with ```{js} into a <script> tag in the HTML document. The JS code is then rendered in the browser when the reader opens the output document!

How do I run an R file in a script?

Type the relevant R function calls into the text file. To run an R command, put the cursor on the line of the command and then click the Run button at the top of the file window. Or just press CTRL-Enter.

Can you run an R script without R?

▶ You can run an R file without explicitly opening R.

What does \r do in JavaScript?

The RegExp \r Metacharacter in JavaScript is used to find the carriage return character (Carriage return means to return to the beginning of the current line without advancing downward). If it is found it returns the position else it returns -1.


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.


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.


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