3

I tried to use t-test in R using OpenCPU as follows -

<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="//cdn.opencpu.org/opencpu-0.4.js"></script>

and

ocpu.seturl("//public.opencpu.org/ocpu/library/stats/R")

var x = [1,2,3,4,5,6,7,8,9,10];
var y = [7,8,9,10,11,12,13,14,15,16,17,18,19,20];
// call R function: stats::t.test
var req = ocpu.rpc("t.test",{
    "x" : x,
    "y" : y
}, function(output){
    alert("t.test equals: " + output);
});

//optional
req.fail(function(){
    alert("R returned an error: " + req.responseText);
});

But I got this error

enter image description here

I am unable to understand where I am going wrong

Dinesh
  • 2,194
  • 3
  • 30
  • 52
  • I've never used that function or that calling convention but it appears that you failed to supply the second argument, namely "stats" that was expected. – IRTFM Dec 21 '15 at 22:28
  • @42- I am not clear abour the "stats" argument.. I included the library in `ocpu.seturl("//public.opencpu.org/ocpu/library/stats/R") ` in the setup. Where else did I miss out? – Dinesh Dec 21 '15 at 22:33
  • See http://jsfiddle.net/jzL22chm/ – Jeroen Ooms Dec 21 '15 at 22:34
  • @Jeroen Thanks for the prompt reply. But is there any way we can get only the `p-value` for the t-test? In `R`, i know we can do it by `t.test(x,y)$p.value` ? – Dinesh Dec 21 '15 at 22:37

1 Answers1

6

The ocpu.rpc function is a shorthand that retrieves the output as JSON. However there is no JSON representation of a t.test object. Therefore you can use ocpu.call and retrieve e.g. the console output from the session [fiddle]:

var req = ocpu.call("t.test",{
    x : x,
    y : y
}, function(session){
  session.getConsole(function(outtxt){
      $("code").text(outtxt);
  });
});

If you want actual data (e.g p-value), I recommend you create an simple R package with a wrapper function that returns a list with data you are interested in:

my_ttest <- function(x, y){
  out <- t.test(x,y)
  list(
    n1 = length(x),
    n2 = length(y),
    p = out$p.value
  )
}

You will be able to call this function using ocpu.rpc as you did above, because the list can be mapped directly to JSON. Note that you can easily deploy your own package on the public demo server with the github webhook.

Jeroen Ooms
  • 31,998
  • 35
  • 134
  • 207
  • Hi thanks for the information. I created a package on github - now how can I call the function in the github package with opencpu? – Dinesh Jun 10 '16 at 16:30
  • got it - `ocpu.seturl("//public.opencpu.org/ocpu/github/githubusername/packagename/R")` – Dinesh Jun 10 '16 at 18:59