问题
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?
回答1:
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>
回答2:
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>
回答3:
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>
来源:https://stackoverflow.com/questions/11418535/how-to-call-an-self-designed-r-function-on-opencpu-via-javascript