OpenCPU provides a full RESTful RPC interface to R. It provides a convenient API to publish, and call R functions. However, a recurring question is “Can I also just run a block of R code?” Of course you can! We created a simple app to illustrate how to do this: http://beta.opencpu.org/apps/opencpu.demo/runcode/. In this post we will elaborate on how this works.
Pushing R code
There are several ways in which you could push a block of R code. One is to use R’s built-in base::identity function. The identity function in R simply returns the value of the argument x. Note that in OpenCPU, arguments that contain R code will automatically be parsed and evaluated. So to run some code, you can simply pass it to the identity function:
Which will yield a JSON representation of this simple line of code.
Multiple lines of code
When you want to run multiple lines of code, there is a few things to keep in mind. First of all, you will have to wrap it in curly braces, as you would have to do in R. Secondly, the last line of the block of code has to specify the value that you want to return (although it is not an actual return as we are not in a function). For a very inefficient way to calculate the sum of squares of the numbers 1 to 100 could be:
We could use exactly the same form in OpenCPU. This play around with pushing code, simply open the app on the demo server: http://beta.opencpu.org/apps/opencpu.demo/runcode/. Make sure to have a look at the source code to see what we are posting to the server.
The Next Step: A function
Pushing some code to the server is nice to get a feel for how OpenCPU works. However in an actual application it is usually bad practice to push have a client push raw R code to the server. Instead you should publish an R function in the OpenCPU store or in the form of a package, and have clients call the R function, while specifying only parameter values. Have a look at this post for an example on publishing functions through the API, and this one on packages and apps.