Calling functions from within R packages in Python using importr - python

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.

Related

How can I fix SyntaxError: invalid syntax/ import * from modbus?

I want to get the .exe file from a code source but doing python main.py build results in this error:
C:\MyProject>python main.py build
Traceback (most recent call last):
File "main.py", line 5, in <module>
import parserz as parser
File "C:\MyProject\parserz.py", line 9
import * from modbus
^
SyntaxError: invalid syntax
Any idea please?
Maybe a problem with pip?
In python you import like this
from modbus import *
Also, In python its good practice to import only what you need.
So you shouldn't use from .... import * instead use
from modbus import something
You can either import the module and run all normal code with
import modbus
or you can import all the classes, functions, variables, etc., from the file to use later in your code with
from modbus import *
To illustrate my point:
If you have two files my_imports.py and main.py that contain the following code:
my_imports.py:
print('Imported module my_imports')
def add_nums(a,b):
return a+b
def another_function():
return 'this function was also called'
(version 1) main.py:
import my_imports
# this code would fail because the function isn't imported
print(add_nums(5,7))
(version 2) main.py:
from my_imports import *
print(add_nums(5,7))
print(another_function())
In verion 1 of main.py you would see Imported module my_imports in the output but your code would fail when you try to use the
add_nums function defined in my_imports.py.
In version 2 of main.py you would still see Imported module my_imports in the output but you would also see the result of calling the other two functions in the output as they are now available for use in main.py:
12
this function was also called
As mentioned in some of the other answers, you can also just import the functionality you want from another python script. For example, if you only wanted to use the add_nums method, you could instead have
from my_imports import add_nums
in your main.py.
Generally from modbus import * should be enough. But it is generally not a good idea to import all so I recommend import modbus as mb. Also you might want to look into modbus libraries like pyModbus or minimalModbus. Here's a good link depicting their pros and cons: Python modbus library

Calling R script from python using rpy2

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.

importing modules from packages in python, such a basic issue I guess I can't even find the answer anyhwere

So my first python program, I downloaded the macholib package from PYPI, then unzipped it and ran installed the setup.py using python install, now I'm trying to run a program where I first import the macholib, then when I try to access methods like Macho, it gives me an error saying macholib module has no attributes called Macho.
My understanding is macholib is a package and not a module or something, hence I cant use the contents of the package.
Please answer, I've wasted too much time on such a simple newbie issue.
running a mac with the latest version of python.
Code:
import sys
import macholib
MachO(DivXInstaller.dmg)
I tried macholib.MachO(DivXInstaller.dmg) and macholib.MachO.MachO(DivXInstaller.dmg)
Error for python test.py
Traceback (most recent call last):
File "test.py", line 3, in <module>
MachO(DivXInstaller.dmg)
NameError: name 'MachO' is not defined
You have this line in your code:
MachO(DivXInstaller.dmg)
However, the name MachO is not defined anywhere. So Python tells you this with the error
NameError: name 'MachO' is not defined
If you want to use the MachO module under the name MachO, you have to import it:
from macholib import MachO
This you have not done, which is the cause of your error. All you did was
import macholib
which gives you the name "macholib" that you can use. However, macholib contains mostly submodules which you can not access like that, so that is not particularly useful. If you don't want to pollute the namespace, you can import MachO as
import machlibo.MachO
Which gives you access to the MachO module as macholib.MachO
You haven't defined DivXInstaller.dmg either, so that's going to be your next error. I recommend that you go through a Python tutorial before you start programming in it.
An import statement defines a namespace. Hence, in order to use something defined in the module or package, you need to qualify it. In this case, the module itself is macholib.MachO but you need to dig deeper, to the actual class MachO which, slightly confusingly, has the same name, so you need to import macholib.MachO and use macholib.MachO.MachO (note that when I try to do this I get an error "DistributionNotFound: altgraph", however).
Note further that it takes a filename as an argument, which is a string. Moreover, you are actually creating an instance of a class, so you probably mean
mlib = macholib.MachO.MachO("DivXInstaller.dmg")
where now mlib is actually the object you need to manipulate with further calls...
Alternately you can do from macholib import MachO or even from macholib.MachO import MachO so you could use MachO.MachO(...) or MachO(...) directly.
This is so simple if you understand Python Packages vs. Modules and import vs. from import:
A Python module is simply a Python source file.
A Python package is simply a directory of Python module(s).
1- import:
import package1.package2.module1
To access module1 classes, functions or variables you should use the whole namespace: package1.package2.modlue1.class1
You cannot import a class or function this way: (wrong)
import package1.package2.class1
2- from ... import
Instead use "from" to import a single class, function or variable of a module:
from package1.package2.module1 import class1
no need to address the whole namespace: class1.method1() works now
Note that you cannot import a method of a class this way
Example:
datetime is a class of module datetime that has a method called utcnow(), to access utcnow() one could:
import datetime
datetime.datetime.utcnow()
Or
from datetime import datetime
datetime.utcnow()

python/jython NameError

im facing typical NameError (without any additional message) on command "cd" while importing other file.
E.g. executor.py
import sys
from java.lang import System
import ds_update
x = ds_update.DataSource()
x.someAction()
And ds_update.py
import sys
from java.lang import System
import sys
from java.lang import System
class DataSource:
def someAction(self):
try:
cd('/')
...
Got error: (if those commands are in one file, there is no problem with cd)
Problem invoking WLST - Traceback (innermost last):
File "...\executor.py", line 17, in ?
File "...\ds_update.py", line 11, in updateDS
NameError: cd
Thank you:-)
You're trying to use a function that isn't defined, namely cd(), according to your comments, it is something provided by WLST. I never used Jython nor WLST, but you have to find a way to import these methods in your script to be able to use them.
there are a few imports needed, namely at least:
import wl
the way to generate the wl module is described by Oracle here http://docs.oracle.com/cd/E15051_01/wls/docs103/config_scripting/using_WLST.html#wp1094333
then you should prefix with "wl." all your "cd" and other WLST built-in commands.
you will find more here
http://www.javamonamour.org/2013/08/wlst-nameerror-cd.html
Even though it is old, I want to add this:
WLST uses a type of namespace. because of this, functions pertaining to wlst don't work if you put the to-be-imported-files not in /wlserver_10.3/common/wlst

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