0

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
  • I understand the basics of `reticulate` and use it in scripts to make those same functions available within R-session. Now i want to move away from having to `reticulate::source_python(math.py)` every time, and instead `library(usefullPyFunctions)` in my projects. – Capture OSM1 Sep 28 '21 at 15:13
  • A simple way would be to write (exported) R functions that call the python code... – dario Sep 28 '21 at 15:13
  • The rJython package uses Jython (java version of python). With it you don't need to install python separately but you do need to install java run time although that is very easy to install. rSymPy is an example which is no longer on CRAN but the source can be used to show how to use it with a large number of python functions. https://cran.r-project.org/src/contrib/Archive/rSymPy/ – G. Grothendieck Sep 28 '21 at 15:24

2 Answers2

0

You can use attach. Alternatively, you could define those as R functions which call the reticulate-wrapped functions.

But as an aside I myself would not want to code it like that since those are not R functions per-se and will make it hard to trace and debug if something goes wrong.

anymous.asker
  • 1,179
  • 9
  • 14
0

You can add an onLoad call to your package to achieve this. Just have the package source those functions on load and then it will work as you mentioned

.onLoad <- function(libname, pkgname){
  x <- rnorm(10)   ## dummy example 
}
tmp
  • 1