Calling R script from python using rpy2 - python

I'm very new to rpy2, as well as R.
I basically have a R script, script.R, which contains functions, such as rfunc(folder). It is located in the same directory as my python script. I want to call it from Python, and then launch one of its functions. I do not need any output from this R function. I know it must be very basic, but I cannot find examples of R script-calling python codes.
What I am currently doing, in Python:
import rpy2.robjects as robjects
def pyFunction(folder):
#do python stuff
r=robjects.r
r[r.source("script.R")]
r["rfunc(folder)"]
#do python stuff
pyFunction(folder)
I am getting an error on the line with source:
r[r.source("script.R")]
File "/usr/lib/python2.7/dist-packages/rpy2/robjects/__init__.py", line 226, in __getitem__
res = _globalenv.get(item)
TypeError: argument 1 must be string, not ListVector
I quite do not understand how the argument I give it is not a string, and I guess the same problem will then happen on the next line, with folder being a python string, and not a R thingie.
So, how can I properly call my script?

source is a r function, which runs a r source file. Therefore in rpy2, we have two ways to call it, either:
import rpy2.robjects as robjects
r = robjects.r
r['source']('script.R')
or
import rpy2.robjects as robjects
r = robjects.r
r.source('script.R')
r[r.source("script.R")] is a wrong way to do it.
Same idea may apply to the next line.

Related

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?
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']
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.

Pass variables between R and Python in R Notebook

When working in an R Notebook:
If I define a variable in an R chunk it is added to the global environment and is accessible to all other R chunks.
```{r}
a = 1 + 4
a
```
However, I haven't been able to pass the variable into a Python chunk or to access R's Global Environment from Python, even using rpy2.
```{python, engine.path="/anaconda/bin/python"}
import rpy2.robjects as robjects
a = robjects.r['a']
print(a[0])
```
Is there a way to do this? If not, I don't see the point of using a non-R language in an R Notebook. I could use Magics in Jupiter Notebook but that doesn't seem as easy.

A first use of python function

Sorry for the very silly question. I am a self-study beginner in python and I am having issues with using a function and calling it. I am coming from a MATLAB background so i was trying to do something similar.
Tools used: Python 2 in a Linux environment
As a test, I created a function that i called prthis (for "print this") within a file called also prthis.py. This function just takes a number as an input, and then outputs two numbers, respectively the same one and its square. I defined it like this:
#----------------------------------------
# content of the file prthis.py
#----------------------------------------
def prthis(x):
y=x*x
nb=x
return (y, nb)
#------------------------------------------
then, within the python prompt, I try to call the newly created prthis function, and I do this:
>>> import prthis
>>> g,t = prthis(7)
The import seems to be succesful, but when I try the function on two outputs variable called g and t , like above, i get the following error message:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'module' object is not callable
Perhaps I am too much MATLAB-izing my thinking. Does anyone has a suggestion on how to deal with this?
PS: it's my first question ever on stackexchange, so please could you let me know how to thank/accept valuable answers from other users? I do not wish to look like ungrateful to those who would try to help.
you are importing a module, not the function. If you want to import just the function you could do this:
from prthis import prthis
g,t = prthis(7)
but if you import the full module you have to define the module you are calling the function from as well:
import prthis
g,t = prthis.prthis(7)
you are successfully able to import prthis but this is not the correct way either you should try "from prthis import prthis. Refer this for a better understanding of calling a function.
What does it mean to "call" a function in Python?

Finding function declarations in Ubuntu on Python

I have a vaguely defined function of a class Graph of a module I call gt (it is graph-tool). so i declare g = gt.graph() then want to use g.degree_property_map but do not know how. Therefore I want to see where in code g.degree_property_map or in this case just the function, is defined. How can I find that? I'm working on command line on a vm.
Thanks
For reference the library in question is graph-tool - http://projects.skewed.de/graph-tool/
Also I am currently importing it using from graph_tool.all import * . that is of course somewhat of a problem.
You could use inspect.getsource(gt.Graph.degree_property_map). (You have to import inspect.)
Of course, what you pass into getsource() will change depending on how you imported Graph. So if you used from graphtools.all import *, you'd just need to use inspect.getsource(Graph.degree_property_map).
If you open interactive python (type python and hit ENTER on the command line), you should be able to run the command help(<graph's module name>), then, under the FILE section of the help documentation that is generated, you should see the absolute path to the code you are interested in.
For example, I just ran:
import numpy
help(numpy)
# Returned documentation containing:
# FILE
# /usr/lib/python2.7/dist-packages/numpy/__init__.py
Also,
import my_module # A module I just created that contains the "Line" class
help(my_module)
# Returned documentation containing:
# FILE
# /home/<my user name>/Programming/Python/my_module.py
If it is a normal function (not a builtin, ufunc, etc) you can try using the func_code attribute
For example:
>>> inspect.iscode
<function iscode at 0x02EAEF30>
>>> inspect.iscode.func_code
<code object iscode at 02EB2B60, file "C:\Python27\lib\inspect.py", line 209>
Never mind I just did help(graph_tool) and manually jumped through code. Thanks for the help though!

how to configure Sweave it's work and recognize for Rpy2?

how to configure Sweave it's work and recognize for Rpy2?
I use this
import rpy2.robjects as robjects
R["library"]("utils")
R["library"]("tools")
R['sweave("/var/www/tmp/pywps/central.Rnw")']
R['texi2dvi("/var/www/tmp/pywps/central.tex", pdf=TRUE)']
but I get these errors
[File "/usr/lib/python2.6/dist-packages/rpy2/robjects/__init__.py", line 241, in __getitem__
res = rinterface.globalenv.get(item)
LookupError: 'Sweave("/var/www/tmp/pywps/central.Rnw")' not found
Traceback (most recent call last):]
thanks for your answers and help
Use square brackets to get an R object, then call it from Python. Or use () brackets to pass a line to R:
R["Sweave"]("/var/www/tmp/pywps/central.Rnw")
R('Sweave("/var/www/tmp/pywps/central.Rnw")')
Sweave needs a capital S (in my tests).
Uh, does this work? You're not doing all the R[] invocations the same way.
import rpy2.robjects as robjects
R["library"]("utils")
R["library"]("tools")
R["sweave"]("/var/www/tmp/pywps/central.Rnw")
R["texi2dvi"]("/var/www/tmp/pywps/central.tex", "pdf=TRUE")
(I've never used Rpy2 so this is totally guessing.)
Using the R package importer would let you use autocompletion in your IDE or interactive shell and make the code more Python-like.
from rpy2.robjects.packages import importr
utils = importr('utils')
utils.Sweave("/var/www/tmp/pywps/central.Rnw")

Categories

Resources