使用导入器从 Python 中的 R 包中调用函数 [英] Calling functions from within R packages in Python using importr

查看:94
本文介绍了使用导入器从 Python 中的 R 包中调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 R 中使用名为 mRMRe 的特征选择算法,但我需要从 Python 中调用它.我已经成功安装了该软件包并能够从 Python 调用它.我需要访问 R mRMRe 包中的一些函数,如 mRMR.data 以将数据帧转换为算法所需的格式.

I am using a feature selection algorithm called mRMRe in R , but I need to call it from Python. I have successfully installed the package and being able to call it from Python. I need to access some functions within the R mRMRe package like mRMR.data to convert the dataframe into a format as needed by the algo.

from rpy2.robjects.packages import importr
utils = importr('utils') #-- Only once.
utils.install_packages('mRMRe')

# Now we begin by loading in the R packages
pymRMR = importr('mRMRe')

pymRMR
Out[53]: rpy2.robjects.packages.Package as a <module 'mRMRe'>

但是,当我尝试调用它的函数 mRMR.data 时出现错误:

However when I try to call it's function mRMR.data I get an error:

AttributeError: module 'mRMRe' has no attribute 'mRMR'

如果我尝试使用不同的库,情况也是如此:

same is the case if I try to do with a different library:

datasets = importr('datasets')
datasets.data.fetch('mtcars')
Traceback (most recent call last):

  File "<ipython-input-56-b036c6da58e1>", line 2, in <module>
    datasets.data.fetch('mtcars')

AttributeError: module 'datasets' has no attribute 'data'

我从 进入链接描述在这里

我不确定我做错了什么.我之前从 mrfDepth 导入了 R 的 medcouple 函数,如下所示:

I am not sure what I am doing wrong. I earlier had imported as used R's medcouple function from mrfDepth as below:

import rpy2.robjects as ro
#now import the importr() method
from rpy2.robjects.packages import importr
utils = importr('utils') #-- Only once.
utils.install_packages('mrfDepth')
# Now we begin by loading in the R packages
mrfdepth = importr('mrfDepth')
mc = mrfdepth.medcouple(yr)[0]
return mc

有人可以帮我解决这个问题吗?

Can someone please help me to resolve this?

推荐答案

您只导入了基本模块,需要完全导入它.你会认为 Python 会自动做到这一点,但显然它不会.请参阅此 SO 答案.

You're only importing the base module, and need to import it entirely. You'd think Python would do that automatically, apparently it doesn't. See this SO answer.

from mRMRr import *
from datasets import *

啊,是的,这适用于显式 python 模块.我认为调用子包函数的语法可能不同.试试这个.

Ah, yeah that applies to explicit python modules. I think the syntax of calling on functions of sub-packages is possibly different. Try this.

import rpy2.robjects.packages as packages
datasets = packages.importr('datasets')
mtcars = packages.data(datasets).fetch('mtcars')['mtcars']

这篇关于使用导入器从 Python 中的 R 包中调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆