How to call an self-designed R function on openCPU via javascript?
Asked Answered
F

3

2

The new openCPU platform allows integration of R functions within HTML/javascript. However I have been struggeling with the implementation. Could somebody provide an example of how to upload your self-designed R function to openCPU and call it with its parameters via javascript?

Ferminafermion answered 10/7, 2012 at 17:19 Comment(2)
there are some apps which you can probably learn from: public.opencpu.org/pages/apps.html in particular, you can take a look at the trick that I used in public.opencpu.org/userapps/opencpu/knitr (call the identity() function with a self-designed R expression)Poree
Hi Yihui! Thanks for your hints. I have tried to deduce some code for a simple example from your app (see blow). I cut out everthing that is not crucial and created some comde that should just run a simple R code following a button press. However there seems to be a mistake which I have not been able to figure out.Ferminafermion
C
3

The solutions above do not work anymore because of modified openCPU server paths and lack of JSON support. Modified working solution

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Call R Through OpenCPU</title> 
  <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
  <script>

      //When Document is Ready
      $(function () {

          //Go R button Click Event Handler
          $("#cmdGoR").click(function () {
              var resultsUrlPrefix = "http://public.opencpu.org",
                  url = resultsUrlPrefix + "/ocpu/library/base/R/identity/save";
              var rCommands = $("#txtRCommands").val();
              $.post(url,
              {
                  x: rCommands
              },
              function (data) {
                
                var statResultsLink = resultsUrlPrefix + data.toString().match(/.+\/stdout/m),
                    chartLink = resultsUrlPrefix + data.toString().match(/.+\/graphics\/[1]/m);
               
                  //Add statistical (textual) results to results div
                  $('#results').append("<br/>");
                  $('<div/>', {
                      id: 'statResults'
                  }).appendTo('#results');
                
                  $("#statResults").load(statResultsLink);

                  //Add charts results to results div
                  $('#results').append("<br/>");
                    $('<img/>', {
                        id: 'chartResults',
                        src: chartLink
                    }).appendTo('#results');

              })
              .error(function (jqXHR, status, error) {
                  alert(jqXHR.responseText);
              });
          });

      });

  </script>
</head>
<body>

<h3>Set of R Commands</h3>
<textarea rows="8" cols="80" id="txtRCommands">

x <- rnorm(1000); 
print(hist(x));

</textarea> 
<br />
<input type="button" value="Run code" id="cmdGoR" />

<div id="results">
</div>

</body>
</html>
Cohosh answered 31/10, 2015 at 8:48 Comment(0)
S
2

Here is a standalone HTML page that does the job. It sends a request to the openCPU server and gets a json object back with keys that point to the appropriate objects on that same server which I then inject into the page. Just download the code and click on the "Run Code" button.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Call R Through OpenCPU</title> 
  <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js">       </script>
  <script>

      //When Document is Ready
      $(function () {

          //Go R button Click Event Handler
          $("#cmdGoR").click(function () {
              var resultsUrlPrefix = "http://public.opencpu.org/R/tmp/";
              var url = "http://public.opencpu.org/R/call/base/identity/save";
              var rCommands = $("#txtRCommands").val();
              $.post(url,
              {
                  x: rCommands
              },
              function (data) {
                  var obj = $.parseJSON(data);

                  //Add statistical (textual) results to results div
                  $('#results').append("<br/>");
                  $('<div/>', {
                      id: 'statResults'
                  }).appendTo('#results');
                  var statResultsLink = resultsUrlPrefix + obj.object + "/print";
                  $("#statResults").load(statResultsLink);

                  //Add charts results to results div
                  var charts = obj.graphs;
                  if (charts.length > 0) {
                      for (var i = 0; i < charts.length; i++) {
                          var chartLink = resultsUrlPrefix + charts[i] + "/png";
                          $('#results').append("<br/>");
                          $('<img/>', {
                              id: 'chartResults' + (i + 1),
                              src: chartLink
                          }).appendTo('#results');
                      }
                  }

              })
              .error(function (jqXHR, status, error) {
                  alert(jqXHR.responseText);
              });
          });

      });

  </script>
</head>
<body>

<h3>Set of R Commands</h3>
<textarea rows="8" cols="80" id="txtRCommands">

x <- rnorm(1000); 
print(hist(x));

</textarea> 
<br />
<input type="button" value="Run code" id="cmdGoR" />

<div id="results">
</div>

</body>
</html>
Stratosphere answered 5/4, 2013 at 19:49 Comment(0)
F
0

Thanks for your hints. I have tried to deduce some code for a simple example from your app (see blow). I cut out everthing that is not crucial and created some comde that should just run a simple R code following a button press. However there seems to be a mistake which I have not been able to figure out.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>openCPU example 1</title>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>

<body>
<div class="container">
<form action="http://public.opencpu.org/R/pub/base/identity/ascii" method="POST" id="knitForm">
<button id="run">Run script</button>
<div id="result"></div>
</form>
</div>
<script>

$('#run').click(function() {
  $('#knitForm').submit();
});

/* attach a submit handler to the form */
$('#knitForm').submit(function(event) {

  /* stop form from submitting normally */
  event.preventDefault(); 

  /* get some values from elements on the page: */
  var $form = $( this ),
      term = ‘{my_func <- function(a,b){plot(a,b);}; my_func(2,3);}‘,
      url = $form.attr('action')

  /* Send the data using post and put the results in a div */
  $.post(url, { term },
    function( data ) {
        $("#result").html(eval(data));
        $('pre code').each(function(i, e) {hljs.highlightBlock(e)});
    })
    .complete(function() {$('#run').attr('class', 'btn');})
    .error(function() { alert("An error occurred!"); });
});
</script>

</body>
</html>
Ferminafermion answered 12/7, 2012 at 12:53 Comment(1)
problems: 1. curly quotes in the line term = ...; 2. the argument for identity() must be named: $.post(url, {x: term}); 3. your function does not return ASCII results, so you will see nothing (read OpenCPU documentation); you can change your code to return(paste(a, b)) for my_func as a test. The knitr demo was a hack for plots which requires deeper understanding of the knitr package, so you'd better read Jeroen's official examples if you want plots.Poree

© 2022 - 2024 — McMap. All rights reserved.