简体   繁体   中英

Integrating R code via rpy2 into a Python package

I'm attempting to build a Python package, and use rpy2 and a handful of R scripts to integrate R seamlessly into that package.

This is code that I've prototyped previously in a Jupyter notebook. What this usually looks like is:

import rpy2

# load in R script containing some useful functions
rpy2.robjects.r("source('feature.R')")

# generate a python binding for 'useful_func' described in the R script
useful_func = rpy2.robjects.globalenv['useful_func']

result = useful_func(data)

This has worked well in Jupyter, as long as all my R scripts are in the same directory as the notebook I'm working with.

The package I'm trying to build looks something like:

package/
 -__init__.py
 -package.py 
 -lib/
  -__init__.py
  -feature1.py
  -feature1.R

I can import feature1 easily, but when it tries to source feature1.R, R can't find the file. I can fix this by providing an absolute path to feature1.R but obviously this won't work when I attempt to distribute the package. How can I generate an absolute path to a resource file within a package in a way that is zip-safe?

...and I figured it out. Answering in case other folks have a similar form of this issue.

In feature1.py:

import importlib.resources as pkg_resources 
import rpy2

with pkg_resources.path('lib', 'feature1.R') as filepath:
    rpy2.robjects.r("source('" + str(filepath) + "')")

useful_func = rpy2.robjects.globalenv['useful_func']

You have resolved yourself the issue with the path in your package. The following is only a mention of convenience code in rpy2 to let you automagically map your R source file to a Python module (just like rpy2 's importr() does, but without the need to have the R code in an R package):

https://rpy2.github.io/doc/v3.1.x/html/robjects_rpackages.html#importing-arbitrary-r-code-as-a-package

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM