I'm trying to pass a function to a function in my opencpu app using ocpu.rpc
. I know the opencpu
API can handle it because I've tested with the sapply
function in base R
(among others) using the API test facility.
However, I've been unable to accomplish the same thing from ocpu.rpc
. I just see HTTP/1.1 400 Bad Request
.
ocpu.rpc("sapply",
{FUN: "sqrt", X: [1,4,9,16,25,36]},
function(output) { output } })
Can anyone provide an example as to how to make this call (and return the JSON vector) using ocpu.rpc
?
I'd ask that you would help me create a jsfiddle
for it, but recently I have been unable to edit fiddles.
It turns out I can use match.fun
to turn the JSON
argument into a function expression on R's side. This is actually what sapply
does by default. I just had the return value wrong. I was basing my code off of the lowess
example, which returns a list with 2 arguments: x
and y
.
//set CORS to call "stocks" package on public server
ocpu.seturl("//public.opencpu.org/ocpu/library/base/R")
//some example data
var mydata = [1, 4, 9, 16, 25];
//call R function: stats::var(x=data)
$("#submitbutton").click(function(){
var req = ocpu.rpc("sapply",{
X : mydata,
FUN : "sqrt"
}, function(output){
$("code").text(output.join("\n"));
});
//optional
req.fail(function(){
alert("R returned an error: " + req.responseText);
});
});