python - 从 get_ipython().magic(u'R ...') 转换为简单的 r2py 命令

标签 python r rpy2

我有一个 Python 脚本(从 IPython Notebook 转换而来),其中包含

def train_mod_inR():
   get_ipython().magic(u'R -i myinput')
   get_ipython().magic(u'R -o res res <- Rfunction(myinput)')
   return res

我试图使用 Python 运行脚本而不使用任何魔法,所以我使用 rpy2。有谁知道有什么简单的方法来翻译上面的函数,使其仅适用于标准 rpy2.例如,是:

def train_mod_inR()
   r2py.robjects('-i myinput')
   r2py.robjects('-o res res <- Rfunction(myinput)')
   return res

事实上,有没有人对此有一个好的解决方法?我有一种感觉,这将需要比我所展示的更多的内容 - r2py 中是否有直接的命令可以让我们像魔术命令一样解释 R?

最佳答案

你已经很接近了。

对魔法中发生的事情的准确翻译是 (注意:定义的对象“converter”是分解正在发生的情况的下一个代码块,暂时假设它只是一个 rpy2 转换器):

from rpy2.robjects.conversion import localconverter

# Take the Python object known as "myinput", pass it to R
# (going through the rpy2 conversion layer), and make it known to R
# as "myinput".
with localconverter(converter) as cv: 
    r2py.robjects.globalenv['myinput'] = myinput
# Run the R function known (to R) as "Rfunction", using the object known
# to R as "myinput" as the argument. Make the resulting object known to
# as "res".
r2py.robjects('res <- Rfunction(myinput)')
# Take the R objects "res", pass it to Python (going through the rpy2
# conversion layer), and make it known to Python as "res".
with localconverter(converter) as cv:
    res = r2py.robjects.globalenv['res']

可以在 R magic ( https://rpy2.github.io/doc/v3.1.x/html/interactive.html#module-rpy2.ipython.rmagic ) 中自定义转换,但假设您使用的是当前默认值(测试是 numpy 还是 pandas已安装留给读者作为练习):

from rpy2.robjects.conversion import Converter
converter = Converter('ipython conversion')
if has_numpy:
    from rpy2.robjects import numpy2ri
    converter += numpy2ri.converter
if has_pandas:
    from rpy2.robjects import pandas2ri
    converter += pandas2ri.converter

请注意,转换可能是一个昂贵的步骤(例如,对于字符串数组,R 和 Python 之间没有 C 级映射,因此必须通过循环复制它们),并且取决于 R 结果的使用方式在代码的其他地方,您可能想要进行更简单的转换(或不进行转换)。

附加评论

现在,人们想要准确地复制 jupyter 中“R magic”单元中发生的情况。核心部分是cell的执行,即字符串的求值:

r2py.robjects('res <- Rfunction(myinput)')

该字符串的计算可以逐步或一次性转移到 Python。在这种情况下,只有后者是可能的,因为只有一个函数调用。 R 称为“Rfunction”的函数可以映射到可调用的 Python 对象:

rfunction = r2py.robjects('Rfunction')

如果您只对 Python 中的 res 感兴趣,则可以在 R 的 globalenv 中创建符号 myinputres code> 可能不再需要,整个可以缩短为:

with localconverter(converter) as cv:
    res = rfunction(myinput)

关于python - 从 get_ipython().magic(u'R ...') 转换为简单的 r2py 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57877575/

相关文章:

python - 如何在webserver上使用python做网页

r - ggplot(散点图)中的 direct.label 不起作用

r - 从 R 中的文本中提取文本引用(字符串)

python - 为什么 Pip 会忽略已配置的具有嵌套依赖项的存储库?

python - 无法在 ubuntu 上配置 rpy2

python - 使用pygame的Python Play声音

python - 使用 python-gnupg 时密码并不重要

r - 在 data.frame() 中移动列而不重新输入

python - 如何在 RPy 中使用 smooth.spline 的 lambda 参数而无需 Python 将其解释为 lambda

python - 为什么他们在旧的 Python 3 版本上有一些新版本的 Python 3?