There’s lots of helpful advice and examples on using R around the web. But what if your visitors could execute and play with simple R examples right on the web page? This is surprisingly easy to do, thanks to a web service and an embeddable widget provided by the Sage project. There are some kinks and caveats, but I think this feature has nice potential for online use in teaching R and statistics.
Sage is an open-source mathematics bundle that includes R, which also includes a server for evaluating code in the languages supported by Sage. What this means is that we can put a editable box on our web page, called a “compute cell”, with R code that a viewer can execute and modify:
You can change this however you want, and execute and see the results by pressing the "Evaluate" button (or pressing Shift+Enter).
How about output files? The Sage server will return those as links that you can download:
Plots show up the same way:
Also, I know there's a way to make Sage remember your input from previous compute cells, but I haven't figured out how to make that happen. Update: In the comments, Alex Kramer and Jason Grout have pointed out a way to do this: specify
linked : true in the call to makeSagecell. More details here.
What version of R do they have and what packages can we use?
As of this writing, it's a year out of date, but that's sure a lot better than many university computer labs. I won't look a gift horse in the mouth!
Embedding the Sage Compute Cell on your Webpage
You can find full documentation on embedding Sage compute cells here. What this won't tell you, however, is how to make the default language R.
Here's how I did it. In the header of your web page, before the CSS link, you load the relevant scripts, as suggested on the official documentation:
Then you need to tel the Sage server how to initialize your compute cell:
languages; these undocumented arguments are how you can make R the default language for the compute cell. (I found this tip here from someone who was using compute cells with GNU Octave.)
The header code makes it so that any time you use
div class="compute", it will create a compute cell:
How do you do this in WordPress.org? I just plopped the header code into my
It would be pretty straightforward to create a simple WordPress plugin to do this, if any readers are feeling especially energetic.
PS: Sage is awesome
I discovered this tool while exploring Sage itself, which is beautiful and very fun. I'm refreshing my linear algebra skills using Robert A. Beezer's wonderful online book, which uses these compute cells with Sage extensively as a teaching tool.