Convert a R script into PythonΒΆ
Links: notebook
, html, PDF
, python
, slides, GitHub
This notebook introduces the function r2python which converts R into Python. It does not work for eveything, it is being improved everytime it is needed.
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 import r2python
print(r2python(rscript, pep8=True))
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 tuple(B . Female[B . Year == y], deces)
It adds some not implemented function such as
colnames(MatDFemale) .set(range((debut + 0), 198))
because the
original syntax colnames(MatDFemale)=debut+0:198
does not work in
Python. The conversion does not fix indices (first position is zero in
Python and 1 in R). The bracket (debut+0):198
are needed to tell
the converter the beginning of the expression. The operator %in%
is
converted into a set intersection.