[Tutor] Python and rpy

Kent Johnson kent37 at tds.net
Thu Dec 21 21:26:11 CET 2006


Geoframer wrote:
> R is a statistical language and Rpy is the python interface for it. 
> However somehow I'm failing to see a step in the python code with which I
> address the R language.
> 
> in R I can do :
> 
> a=diag(10)                              #produces an identity matrix of 
> size 10
> b=kmeans(a,2,5,10,"Forgy")    #calculate a kmeans clustering algorithm 
> on the 10 vectors contained by the matrix just declared.
> 
> 
> in Ipython this does :
> 
> ---------
> In [1]: from rpy import *
> RHOME= C:\Program Files\R\R-2.4.0
> RVERSION= 2.4.0
> RVER= 2040
> RUSER= C:\Documents and Settings\Ronald
> Loading the R DLL C:\Program Files\R\R-2.4.0\bin\R.dll .. Done.
> Loading Rpy version 2040 .. Done.
> Creating the R object 'r' ..  Done
> 
> In [2]: a = r.diag(10)
> 
> In [3]: b = r.kmeans(a,2,10,5,"Forgy")
> ---------------------------------------------------------------------------
> rpy.RException                                Traceback (most recent 
> call last)
> 
> C:\Python24\<ipython console>
> 
> RException: Error in as.double.default(x) : (list) object cannot be 
> coerced to '
> double'
> ---------

This seems to work, it keeps a in the internal R representation instead 
of converting it to a list of lists:

In [1]: from rpy import *
RHOME= C:\Program Files\R\R-2.3.1
RVERSION= 2.3.1
RVER= 2031
RUSER= G:\
Loading the R DLL C:\Program Files\R\R-2.3.1\bin\R.dll .. Done.
Loading Rpy version 2031 .. Done.
Creating the R object 'r' ..  Done

In [22]: aa=with_mode(NO_CONVERSION, r.diag)(10)

In [25]: b=r.kmeans(aa,2,10,5,"Forgy")

In [26]: b
Out[26]:
{'centers': [[0.1111111111111111,
               0.1111111111111111,
               0.1111111111111111,
               0.1111111111111111,
               0.0,
               0.1111111111111111,
               0.1111111111111111,
               0.1111111111111111,
               0.1111111111111111,
               0.1111111111111111],
              [0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0]],
  'cluster': [1, 1, 1, 1, 2, 1, 1, 1, 1, 1],
  'size': [9, 1],
  'withinss': [8.0000000000000018, 0.0]}

 > I've tried numerous things to get it to work, but i basically can not
 > find out how i do something as simple as the two statements in R in
 > RPython. Apparently something is going wrong somewhere in the conversion
 > of python objects to R objects but i can't seem to fix it. There is a
 > code snippet in the RPy-reference manual but it's only valid for python
 > 2.2 and 2.1 and i couldn't get it to work on 2.4.

Where is the snippet?

Cheers,
Kent



More information about the Tutor mailing list