Coming from data science I can write my own (project specific) R-libraries following hadleys book, but struggle to grasp the more high level software dev jargon. I want to incorporate python functions lying around from previous data scientists without the need to rewrite them in R. Therefore I am looking for a minimal example of wrapping python functions into an R-package.
In Attaching python script while building r package
the python script is used inside the body of an R function presumably to solve a specific task within the r function. What if the python script contains a set of functions i want to have available after loading myRpackage
.
For example: given the
script math.py
def square(x):
return x * x
def cube(x):
return x * x * x
Create a package mathR
that
library(MathR)
square(2)
# 4
cube(2)
# 8
How to expose functions in python script as stand-alone functions within an r-package?
EDIT: Here is my first approach. pymath.R
math <- function(){
out <- reticulate::py_run_file(system.file("python/math.py", package = "mathR"))
return(out)
}
However, this requires me to initialize math()
to expose the functions, whereas I would like to have them available directly after loading the package as in above.
library(mathR)
math_functions <- math()
math_functions$square(2)
# 4