The speedup is breathtaking.
You can see that writing certain functions in C can be worth the effort.
This is especially true for functions that involve iteration, as R’s own itera-
tion constructs, such asfor(), are slow.
15.2 Using R from Python........................................................
Python is an elegant and powerful language, but it lacks built-in facilities for
statistical and data manipulation, two areas in which R excels. This section
demonstrates how to call R from Python, using RPy, one of the most popular
interfaces between the two languages.
15.2.1 Installing RPy...................................................
RPy is a Python module that allows access to R from Python. For extra effi-
ciency, it can be used in conjunction with NumPy.
You can build the module from the source, available fromhttp://rpy
.sourceforge.net, or download a prebuilt version. If you are running Ubuntu,
simply type this:
sudo apt-get install python-rpy
To load RPy from Python (whether in Python interactive mode or from
code), execute the following:
from rpy import*
This will load a variabler, which is a Python class instance.
15.2.2 RPy Syntax.....................................................
Running R from Python is in principle quite simple. Here is an example of a
command you might run from the>>>Python prompt:
>>> r.hist(r.rnorm(100))
This will call the R functionrnorm()to produce 100 standard normal
variates and then input those values into R’s histogram function,hist().
As you can see, R names are prefixed byr., reflecting the fact that
Python wrappers for R functions are members of the class instancer.
The preceding code will, if not refined, produce ugly output, with your
(possibly voluminous!) data appearing as the graph title and thex-axis label.
You can avoid this by supplying a title and label, as in this example:
>>> r.hist(r.rnorm(100),main='',xlab='')
RPy syntax is sometimes less simple than these examples would lead you
to believe. The problem is that R and Python syntax may clash. For instance,
330 Chapter 15