Using R with Sage: R in the Sage notebook
Greater Boston R User Group
R in the New Year Lightning Talk
January 17th, 2012 - Bocoup Loft, Boston
Speaker: Karl-Dieter Crisman, Gordon College (MA)
This talk has three purposes:
Sage (www.sagemath.org) is a comprehensive mathematics software package, whose general goal is to create "a viable free open source alternative to Magma, Maple, Mathematica and Matlab." If this sounds ambitious, it is. Part of the key is broad but high-quality functionality (about which more in a moment).
Sage has just about all of the usual functionality you associate with the various mathematics programs starting with "M".
arctan(x) arctan(x) |
Maxima gives good symbolic calculus functionality, and the matplotlib Python library gives nice graphics - all wrapped in a unified, easy-to-use interface.
|
Sage is built on Python, so of course objects persist and we can access object-oriented methods.
|
|
|
|
|
This function is, of course, f(x)=e^x, and Sage has calculated and typeset its Taylor series on the fly.
Notice that I can incorporate nearly arbitrary LaTeX in the notes, thanks to the jsmath Javascript package (soon to be upgraded to MathJax), and ask Sage to typeset the answers nicely (this can also be done with the 'Typeset' checkbox at the top).
Sage also has extensive research-level tools, especially in algebraic geometry and number theory. Michael Rubinstein's L-function calculator, for example, is state-of-the-art in such calculations. Here, we verify the Riemann Hypothesis in a small range.
[(101.317851, 0.290553812), (103.725538, 0.115642480), (105.446623, 0.0363238092), (107.168611, -0.190935080)] [(101.317851, 0.290553812), (103.725538, 0.115642480), (105.446623, 0.0363238092), (107.168611, -0.190935080)] |
Notice that Sage has some nice interactive help, just like R, in case one isn't sure what exactly this module does.
|
File: /Users/karl-dietercrisman/Desktop/sage-4.4.4/local/lib/python2.6/site-packages/sage/lfunctions/lcalc.py Type: <class ‘sage.lfunctions.lcalc.LCalc’> Definition: lcalc(args) Docstring:
File: /Users/karl-dietercrisman/Desktop/sage-4.4.4/local/lib/python2.6/site-packages/sage/lfunctions/lcalc.py Type: <class ‘sage.lfunctions.lcalc.LCalc’> Definition: lcalc(args) Docstring:
|
Sage has many more respected open-source packages inside it. Here is a (not very interesting) modeling example using Scipy - again, with Sage syntax.
|
|
This is in addition to many, many lines of new code for a wide variety of purposes.
Simplicial complex with vertex set (1, 3, 7) and facets {(3, 7), (1,)}
Simplicial complex with vertex set (1, 3, 7) and facets {(3, 7), (1,)}
|
Pressing [tab] after the dot gives all applicable methods, as one might expect in an object-oriented context.
|
|
For much more, including introductions to Sage and its capabilities at various levels, see www.sagemath.org.
Well, when it comes to state-of-the-art open source answers for statistics, R is in a class of its own! So, naturally, Sage includes R as a standard package.
It is possible to access R directly from a Sage installation through from a shell via the command sage -R, or inside a Sage command line instance via r_console(). There is also a library-level interface called "rpy" (now "rpy2") many of you may be familiar with, which is included in Sage.
However, we will focus here on using R (directly or indirectly) from the wonderful "notebook" interface this talk is in. Most of this talk can be run from any web browser anywhere in the world, as long as you can find a public Sage server to do it from (such as www.sagenb.org), though for a few things we will need optional R packages to be installed. This actual talk is located at FIXME, and you can create an account and edit a copy as we speak!
There are two main ways to access R in the notebook. The more obvious is to put a "percent directive" in a cell and just use normal R commands. This first example is reminiscent of examples in John Verzani's introductory statistics with R book.
[1] 22.36559
MPG.city
Origin 15 16 17 18 19 20 21 22 23 24 25 26 28 29 30 31 32 33 39 42 46
USA 2 3 4 5 8 3 3 4 7 2 2 0 1 2 0 2 0 0 0 0 0
non-USA 0 0 4 7 2 5 3 3 1 3 4 2 1 4 1 0 1 1 1 1 1
[1] 22.36559
MPG.city
Origin 15 16 17 18 19 20 21 22 23 24 25 26 28 29 30 31 32 33 39 42 46
USA 2 3 4 5 8 3 3 4 7 2 2 0 1 2 0 2 0 0 0 0 0
non-USA 0 0 4 7 2 5 3 3 1 3 4 2 1 4 1 0 1 1 1 1 1
|
Or you can use the syntax r.r_command instead. This is especially helpful for using things right away in Sage constructs.
quartz_off_screen
2
quartz_off_screen
2
|
This example is due to Andrzej Giniewicz.
|
Here is an example showing how to combine Sage interacts (similar to RStudio's manipulate) with R. Here, I'm just showing graphically that random samples from a normal distribution look more and more like what they should as the samples get bigger.
Click to the left again to hide and once more to show the dynamic interactive window |
There are three things you can see with this example.
These are, of course, really just examples of using R through the Sage notebook, not really using Sage and R together. What about interactions?
The larger point is that R and Sage have complementary capabilities, and it is relatively easy to pass things back and forth between them.
Rather than try to make up an example of interest to you, I will show you one I have used, in the mathematical theory of social choice (games, voting, etc.). This is a real-life situation where:
Sound familiar?
Here, I use the only easily accessible open-source implementations of computing the so-called mediancentre of a data set - both of which are in R optional packages! - and then exploit Sage's graphics, optimized combinatorics, and interactive capabilities to visualize them.
Click to the left again to hide and once more to show the dynamic interactive window |
The code for this is below (as is the evidence that I installed the "orloca" package while preparing the talk). The important part isn't the code itself, but rather the following points about the integration of Sage and R. For many of you, this will be the main point of the talk!
The utility of R to Sage, and the immense benefit of being able to use advanced statistics packages along with robust calculus, number theory, and so forth within a nice GUI with interactive capabilities should be clear.
However, in what ways can the main Sage project be useful to the R project?
\newcommand{\Bold}[1]{\mathbf{#1}}\hbox{Orthogonal representation of the symmetric group corresponding to [3, 1, 1]}
\newcommand{\Bold}[1]{\mathbf{#1}}\hbox{Orthogonal representation of the symmetric group corresponding to [3, 1, 1]}
|
Thanks to:
R version 2.10.1 (2009-12-14)
Copyright (C) 2009 The R Foundation for Statistical Computing
ISBN 3-900051-07-0
R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.
Natural language support but running in an English locale
R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.
Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.
> options(repos="http://cran.r-project.org/");
install.packages("orloca")
trying URL 'http://cran.r-project.org/src/contrib/orloca_3.2.tar.gz'
Content type 'application/x-gzip' length 13188 bytes (12 Kb)
opened URL
==================================================
downloaded 12 Kb
* installing *source* package ‘orloca’ ...
** R
** demo
** inst
** preparing package for lazy loading
Warning in matchSignature(signature, fdef, where) :
in the method signature for function "coerce" no definition for class:
“loca.p”
Warning in matchSignature(signature, fdef, where) :
in the method signature for function "coerce" no definition for class:
“loca.p”
Warning in matchSignature(signature, fdef, where) :
in the method signature for function "coerce" no definition for class:
“loca.p”
Warning in matchSignature(signature, fdef, where) :
in the method signature for function "coerce" no definition for class:
“loca.p”
Creating a new generic function for "as.matrix" in "orloca"
Warning in matchSignature(signature, fdef, where) :
in the method signature for function "as.matrix" no definition for
class: “loca.p”
Creating a new generic function for "as.data.frame" in "orloca"
Warning in matchSignature(signature, fdef, where) :
in the method signature for function "as.data.frame" no definition for
class: “loca.p”
Warning in matchSignature(signature, fdef, where) :
in the method signature for function "czsum" no definition for class:
“loca.p”
Warning in matchSignature(signature, fdef, where) :
in the method signature for function "czsumgra" no definition for
class: “loca.p”
Warning in matchSignature(signature, fdef, where) :
in the method signature for function "czsummin" no definition for
class: “loca.p”
Creating a new generic function for "summary" in "orloca"
Creating a new generic function for "print" in "orloca"
** help
*** installing help indices
** building package indices ...
* DONE (orloca)
The downloaded packages are in
‘/private/var/folders/Yy/YytEJm5VEB0+pBRD7JNLe++++TQ/-Tmp-/RtmpYisoeC/d\
ownloaded_packages’
Updating HTML index of packages in '.Library'
>
real 0m6.367s
user 0m2.480s
sys 0m0.244s
Please restart Sage in order to use 'orloca'.
R version 2.10.1 (2009-12-14)
Copyright (C) 2009 The R Foundation for Statistical Computing
ISBN 3-900051-07-0
R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.
Natural language support but running in an English locale
R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.
Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.
> options(repos="http://cran.r-project.org/"); install.packages("orloca")
trying URL 'http://cran.r-project.org/src/contrib/orloca_3.2.tar.gz'
Content type 'application/x-gzip' length 13188 bytes (12 Kb)
opened URL
==================================================
downloaded 12 Kb
* installing *source* package ‘orloca’ ...
** R
** demo
** inst
** preparing package for lazy loading
Warning in matchSignature(signature, fdef, where) :
in the method signature for function "coerce" no definition for class: “loca.p”
Warning in matchSignature(signature, fdef, where) :
in the method signature for function "coerce" no definition for class: “loca.p”
Warning in matchSignature(signature, fdef, where) :
in the method signature for function "coerce" no definition for class: “loca.p”
Warning in matchSignature(signature, fdef, where) :
in the method signature for function "coerce" no definition for class: “loca.p”
Creating a new generic function for "as.matrix" in "orloca"
Warning in matchSignature(signature, fdef, where) :
in the method signature for function "as.matrix" no definition for class: “loca.p”
Creating a new generic function for "as.data.frame" in "orloca"
Warning in matchSignature(signature, fdef, where) :
in the method signature for function "as.data.frame" no definition for class: “loca.p”
Warning in matchSignature(signature, fdef, where) :
in the method signature for function "czsum" no definition for class: “loca.p”
Warning in matchSignature(signature, fdef, where) :
in the method signature for function "czsumgra" no definition for class: “loca.p”
Warning in matchSignature(signature, fdef, where) :
in the method signature for function "czsummin" no definition for class: “loca.p”
Creating a new generic function for "summary" in "orloca"
Creating a new generic function for "print" in "orloca"
** help
*** installing help indices
** building package indices ...
* DONE (orloca)
The downloaded packages are in
‘/private/var/folders/Yy/YytEJm5VEB0+pBRD7JNLe++++TQ/-Tmp-/RtmpYisoeC/downloaded_packages’
Updating HTML index of packages in '.Library'
>
real 0m6.367s
user 0m2.480s
sys 0m0.244s
Please restart Sage in order to use 'orloca'.
|
Traceback (click to the left of this block for traceback) ... there is no package called 'orloca' Traceback (most recent call last): ##########################################################################
File "", line 1, in <module>
File "/tmp/tmpb9yLa3/___code___.py", line 32, in <module>
r.library('orloca')
File "/sagenb/sage_install/sage-4.7.2/local/lib/python2.6/site-packages/sage/interfaces/r.py", line 572, in library
raise ImportError, "%s"%ret
ImportError: Loading required package: orloca
Warning message:
In library(package, lib.loc = lib.loc, character.only = TRUE, logical.return = TRUE, :
there is no package called 'orloca'
|
|
|