0

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.

opencpu accepts functions as arguments

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.

jquery or opencpu has been blocked

wdkrnls
  • 4,548
  • 7
  • 36
  • 64
  • This jsfiddle editing issue seems to be happening intermittently wherever I am. I'm wondering if they just don't preserve javascript library load order and it works half the time by chance. – wdkrnls Jan 11 '16 at 03:51

1 Answers1

0

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); 
    });
});
wdkrnls
  • 4,548
  • 7
  • 36
  • 64