Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Python to R

Tags:

python

r

I know there exists a module (rpy and rpy2) to convert R code to Python.

Is there any easy way to do the reverse?

like image 550
numegil Avatar asked Oct 28 '11 18:10

numegil


2 Answers

rpy(2) does not convert code. It only allows you an interface to communicate with R from python and issue R commands from within python.

Given that R is very dependent upon statistical libraries that aren't available in python the conversion would generally be a tremendous amount of work. To convert a single line like

lmer (y ~ x1 + x1 + (1|id), mydat)

to something in python would take a great deal of work. If you just want to run that code from python use rpy. Going the other way, which seems to be more what you are interested in, the conversion could often be a bit more straightforward. However, the code would tend to be very poorly optimized for R and run very badly. I recently optimized some R code converted from python by someone who wrote the R code as a more or less direct translation line by line. The optimization came out 1/3 the length and between 20 and 1000 times faster (depending on the function).

like image 92
John Avatar answered Sep 29 '22 10:09

John


John is correct. These are not converting between languages, but interfacing languages. Language conversion is not particularly common, though interfacing them is. However, object conversion is quite common, as that is an important part of interfacing languages.

In addition to Rpy and Rpy2, take a look at RSPython. It also provides for object conversion, and inspired Rpy.

like image 23
Iterator Avatar answered Sep 29 '22 12:09

Iterator