Posts tagged .net

Running R in an Azure C# WebJob

I had the task to run R in an C# azure web job, I could of used the Azure Machine Learning Studio in order to run the R script, and executed this process via a web call. But I wanted the ability to potentially host this app outside of Azure, an a simple C# web app would allow me that with simple modifications.

This was my first time looking at R, so I had to spend quite a bit of time in R Studio to get to grips with the basics of running the scripts and handling packages. The next step was to decide on how to run the script, after a bit of searching I found the RDotNet nuget package which promised to provide a simple way of running pieces of R code within .net.

The simplest example I got running to prove the concept:

This expects a standard installation of R on your windows machine, I believe it can handle installations on unix and mac if running in mono. This script ran perfectly, I was able to get this running nicely in Linqpad as well. The next issue faced was how to get this running if you dont have a standard installation of R, as would be the case with the Azure web app.

The SetEnviromentVariables call accepts to parameters, rPath and rHome, so if your installation was else where, or even running from a usb stick or network drive you could still use RDotNet. With some lots of searching on StackOverflow, I finally found what paths the SetEnvironmentVariables call was expecting. I copied my installation of R to a new dir and updated my linqpad script with the following:

The script continued to run successfully, so with the concept proved I could move onto creating the Azure web job. Using the Kudu tools website (https://<WEB_APP_NAME>.scm.azurewebsites.net/DebugConsole), I copied the R-3.3.2 folder and its contents to /site/wwwroot/,

Web Job Folder Structure

Web Job Folder Structure

and updated the rPath and rHome variables to these new locations:Pushing the new web app and letting it run, provided the same output ’10′ in the azure streaming logs for the app. Success!

Packages

Soon after getting the basic R script running I ran into issues adding new packages, the basic error boiled down to not having rights access to download or install new packages. (There may be a simple way round this, such as changing where R is located on the web app, or some config settings).

The work around involved downloading the package I was looking to use, in this case RODBC, and uploading the zip to the web app, you can see my packages folder in the screenshot above. Next you have to install this package in your R script, I achieved this with the following: