Shuvayan Das
Shuvayan Das

Reputation: 1048

Calling functions from within R packages in Python using importr

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'>

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'

I got this datasets part from enter link description here

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?

Upvotes: 2

Views: 3825

Answers (2)

Alireza Honarfar
Alireza Honarfar

Reputation: 105

I used to import some R packages ans use them inside my python code but recently I improvised a method where you can simply use your R code and give the required tasks to it. Have a look here https://stackoverflow.com/a/55900840/5350311 it can be useful for your case.

Upvotes: 0

Anonymous coward
Anonymous coward

Reputation: 2091

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 *

Edit: 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']

Upvotes: 3

Related Questions