[英]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. 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.这是我之前在 Jupyter 笔记本中原型化的代码。 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.这在 Jupyter 中运行良好,只要我所有的 R 脚本与我正在使用的笔记本位于同一目录中。
The package I'm trying to build looks something like:我正在尝试构建的 package 看起来像:
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.我可以轻松导入 feature1,但是当它尝试获取 feature1.R,R 时找不到该文件。 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.我可以通过提供 feature1.R 的绝对路径来解决这个问题,但是当我尝试分发 package 时,这显然不起作用。 How can I generate an absolute path to a resource file within a package in a way that is zip-safe?如何以 zip 安全的方式生成 package 中资源文件的绝对路径?
...and I figured it out. ......我想通了。 Answering in case other folks have a similar form of this issue.回答以防其他人有类似的问题。
In feature1.py:在 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.您已经解决了 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): 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 https://rpy2.github.io/doc/v3.1.x/html/robjects_rpackages.html#importing-arbitrary-r-code-as-a-package
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.