module languages.rconverter

Short summary

module pyensae.languages.rconverter

Convert R into Python

source on GitHub

Functions

function

truncated documentation

r2python

Converts a R script into Python.

Documentation

Convert R into Python

source on GitHub

pyensae.languages.rconverter.r2python(code: str, pep8=False, fLOG=None) str

Converts a R script into Python.

Parameters:
  • code – R string

  • pep8 – modify the output to be compliant with pep8

  • fLOG – logging function

Returns:

Python string

The function uses a customized R grammar implemented with Antlr4. Formula becomes strings. They should be handled with patsy.

Convert R into Python

<<<

rscript = '''
    nb=function(y=1930){
    debut=1816
    MatDFemale=matrix(D$Female,nrow=111)
    colnames(MatDFemale)=(debut+0):198
    cly=(y-debut+1):111
    deces=diag(MatDFemale[:,cly[cly%in%1:199]])
    return(c(B$Female[B$Year==y],deces))}
    '''

from pyensae.languages.rconverter import r2python
print(r2python(rscript, pep8=True))

>>>

    ANTLR runtime and generated code versions disagree: 4.13.0!=4.10.1
    ANTLR runtime and generated code versions disagree: 4.13.0!=4.10.1
    /usr/local/lib/python3.9/site-packages/autopep8.py:1726: PendingDeprecationWarning: lib2to3 package is deprecated and may not be able to parse Python 3.10+
      from lib2to3 import pgen2
    from python2r_helper import make_tuple
    
    
    def nb(y=1930):
        debut = 1816
        MatDFemale = matrix(D . Female, nrow=111)
        colnames(MatDFemale) .set(range((debut + 0), 198))
        cly = range((y - debut + 1), 111)
        deces = diag(MatDFemale[:, cly[set(cly) & set(range(1, 199))]])
        return make_tuple(B . Female[B . Year == y], deces)

Some patterns are not well migrated such expression a:b into range(a,b). The grammar could be improved to detect the beginning of the expression but for now, if the function fails to do the conversion, a:b must be written into (a):b. The same trick is sometimes needed for other patterns such as the operator %in% which is converted into an intersection of two sets.

Kwonws bugs:

  • } else { needs to be replaced by } EOL else {

  • comment added at the end of line must be followed by an empty line

  • m[,1] must be replaced by M[:,1]

  • formula ~. is not translated

  • %<% cannot be followed by an empty line

The grammar were updated in 2022 for python 3.10 and antlr4-python3-runtime == 4.10.

source on GitHub