Rmagic in IPython
This files is part of the examples collection of the Sagemath Cloud.
Rmagic is an extension for IPython. Check out the full IPython notebook for additional details! It is based on RPy2 and allows to seamlessly talk to an underlying R session via an IPython notebook.
To activate it, see the cell below. There are basically only a few core commands:
%R
runs a line of R code, return values can be assigned viavar = %R ...
.%%R -i <input> -o <output> ...
runs the entire cell in R and-i
and-o
specify the variables for input and output.%Rpush ...
sends the data of a given variable to R.%Rpull ...
retrieves the variable (namespace is populated) and the data of a variable inside R.%Rget ...
is similar toRpull
, but only retrieves the actual data.
a
only exists in R, hence the following error:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-5-60b725f10c9c> in <module>()
----> 1 a
NameError: name 'a' is not defined
%Rget
pulls and converts the data into Python:
%Rpull
is similar, and defines the variable, too:
%%R
runs the given cell in R and -o [variable]
"outputs" it to Python
Plots
Basically, they are stright forward. Multiple simultaneous plots are displayed accordingly.
Interested in the coefficients?
Use R's slot accessor $
via a call to R in %R
to retrieve the coefficients as a NumPy array.
Plotting in a 2x2 grid via R's par
command and setting the output canvas size to 800x600 pixels.
Advanced Example: PCA
The pca_usarrest
variable references a datastructure from R. Applying R functions via RPy2 directly is no problem.