Download - All IT eBooks

Transcript
Using External Modules: The Python Interface to R ◾ 231 [1]
>>>
>>>
[1]
>>>
[1]
1 2 3 4 5 6 7 8 9 10
s = r['seq']
print s(1,10)
1 2 3 4 5 6 7 8 9 10
print r('seq(1,10)')
1 2 3 4 5 6 7 8 9 10
#dictionary-like
#function-like
Q & A: WHICH OF THE THREE WAYS TO ACCESS
R OBJECTS SHOULD I USE?
Our suggestion is this: the simpler the better, but much depends on your
preferences. You might even decide to mix the different ways to get R
objects in a Python program. For example, r.pi looks slightly simpler
than r('pi'), but you may prefer the latter. In all cases, you have to
remember that the result of retrieving an R object in Python is always
an R vector; therefore, you have to use indexing to specifically access its
elements.
13.3.4 Creating Matrices
You can create a matrix in R as follows:
> y = seq(1,10)
> matrix(y, ncol = 5)
[,1][,2] [,3][,4][,5]
[1,] 13 579
[2,] 2 4 6 810
>
In Python, you have to convert both seq() and matrix() R functions
into Python objects using robjects.r. You can do it in the same three
ways as in Section 13.3.3.
Accessing R Functions as Attributes of robjects.r
Using the Dot Syntax
>>> import rpy2.robjects as robjects
>>> r = robjects.r
>>> y = r.seq(1,10)
>>> print r.matrix(y, ncol = 5)
[,1][,2] [,3][,4][,5]
[1,] 13 579
[2,] 2 4 6 810