如何通过javascript在openCPU上调用自行设计的R函数?

时间:2012-07-10 17:19:57

标签: javascript r opencpu

新的openCPU平台允许在HTML / javascript中集成R个功能。但是我一直在努力实施。有人可以举例说明如何将自行设计的R函数上传到openCPU并通过javascript调用它的参数吗?

3 个答案:

答案 0 :(得分:2)

这是一个完成工作的独立HTML页面。它向openCPU服务器发送一个请求,并获取一个json对象,其中的键指向同一服务器上的相应对象,然后我将其注入页面。只需下载代码并单击“运行代码”按钮。

<!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>

答案 1 :(得分:2)

由于修改后的openCPU服务器路径和缺少JSON支持,上述解决方案不再起作用。修改后的工作解决方案

<!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>

答案 2 :(得分:0)

感谢您的提示。我试图从你的应用程序推导出一些简单例子的代码(见打击)。我删除了并不重要的everthing,并创建了一些comde,只需在按下按钮后运行一个简单的R代码。然而,似乎有一个我无法弄清楚的错误。

<!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>