Last time we demonstrated with a simple example how to publish a function to OpenCPU that generates an on-demand plot. In this post we will take the next step: we put the R function into an R package and made an ‘app’ for it. We use an example that was contributed by Thomas Zumbrunn from the university of Basel.
If you can’t wait, click here for the app: http://beta.opencpu.org/apps/opencpu.demo/nabel.
Swiss Air pollution Data
After reading our previous post, Thomas posted a similar function (using e.g. this form) on the public demo server that downloads live data from Swiss National Air Pollution Monitoring Network (NABEL), and plots it using lattice. To call the function, simply open:
Because OpenCPU is open source by design, we can have a look at the source code which is by definition available under AGPL. E.g we can have a look at:
Packaging your function
Posting functions on an OpenCPU server through the API is a great way to get started with OpenCPU. But once you perfected your function and it is doing what you want it to do, you want to move it to a more permanent place, maybe refactor it into smaller functions, document it, etc. R has a very natural system to accomplish this: a package.
Because we liked Thomas example so much, we decided to modify it a bit and include it in the opencpu.demo R package. There are many advantages of having your function into a package. We can now easily install it on other OpenCPU servers, and can use the name of the function to call it:
To see the source code of a function in a package, we could use R’s identity function:
Furthermore, the documentation of the function is automatically published. Hence we can communicate to others how they should be calling the url:
From the documentation, clients developers will be able to infer the function parameters. For example, to get temperature data from the last week:
Run function locally
OpenCPU defines a direct mapping between an R function and the RPC call. An additional advantage of putting your function in a package is that people can easily inspect the function on their local computer. For example, the calls above can be performed on your local machine as well:
The Nabel App
An additional advantage of using packages in OpenCPU is that you can include ‘apps‘. An app is a client web application for your R functions that you can include in your R package and will automatically be deployed on OpenCPU. In our next post we will go into more details about OpenCPU apps. We included a little demo app for the Nabel function in the opencpu.demo package. It is available at:
To see the source code of the app, simply download the opencpu.demo package source from CRAN, and look in the /inst/opencpu/apps/ directory. In our next blog post we will go in a little more detail about OpenCPU apps.