Part of what attracted me to R was the ease and efficiency in using the language for tasks for which it was designed. R is a tool among that can be used to do great things with minimal effort. This post illustrates some other tools and technologies that provide the building blocks for quickly creating web applications. And by adding an extra 3 lines of code, a url is included in the web application that can be accessed by R to draw the chart above.
The JQuery tutorials include an example on how to make Ajax calls that allow a user to enter a vote by clicking on a link. The specific example they use requires a php page. I am partial to ruby and so the code associated with this post provides a similar version using Sinatra.
The app.rb file contains modifications to the ruby array class (so that collections of integers will return their count and average). Some configuration is included to reset the application (which allows for changes to code without starting/restarting the server). The index page contains the jquery code in the tutorial. The process_vote post handler opens a file named stored_ratings.txt and writes the value clicked on by a user (an integer between 1 and 5). It returns a bit of xml that contains the ratings and size of the array.
When you start the app and open http://localhost:4567 in a browser, you are greeted with a page that allows you to click a number as a rating.
Please rate: 1 2 3 4 5
After choosing a link, the value is posted to the server and a response is sent back. Simply click the browser refresh to return to the “Please rate” page where you started. After repeating this process and voting a bunch of times, the message I received was.
Thanks for rating, current average: 3.23529411764706, number of votes: 17
The R commands which calls this server simply reads the lines available at the http://localhost:4567/data url. This returns the stored_ratings.txt file and demonstrates that the values returned are the same as those available on the server.
A plot of the data results in the bar plot displayed above.
qplot(votes, binwidth=1, fill=..count..) +
scale_fill_gradient(“Count”, low=”darkgreen”, high=”lightgreen”)
Code associated with this post is available from this github repository.