Issues importing some R packages to python - python

I want to import SCI package from R to Python
So i did this code:
Source: How to import r-packages in Python
# Using R inside python
import rpy2
import rpy2.robjects.packages as rpackages
from rpy2.robjects.vectors import StrVector
from rpy2.robjects.packages import importr
utils = rpackages.importr('utils')
utils.chooseCRANmirror(ind=1)
# Install packages
packnames = ('SCI')
utils.install_packages(StrVector(packnames))
# Load packages
sci = importr('SCI')
But when i run:
utils = rpackages.importr('utils')
i get this error:
NotImplementedError: Conversion 'rpy2py' not defined for objects of type '<class 'rpy2.rinterface.SexpClosure'>'
and when i run :
utils.chooseCRANmirror(ind=1)
i get this:
NotImplementedError: Conversion 'py2rpy' not defined for objects of type '<class 'int'>'
How can i import this package to Python?
Thanks in advance.

Related

Using rpy2 to install additional packages failing from jupyter lab

I am trying to call R from within some python code using the rpy2 library. I need to use non-base packages, but keep on running into the following hiccup. Thanks for considering! Most of the code is copy-pasted from the manual.
import rpy2
import rpy2.robjects as robjects
from rpy2.robjects.packages import importr
# import rpy2's package module
import rpy2.robjects.packages as rpackages
base = importr('base')
# import R's utility package
utils = rpackages.importr('utils')
# select a mirror for R packages
utils.chooseCRANmirror(ind=1) # select the first mirror in the list
# R package names
packnames = ('pROC', 'bootLR')
# R vector of strings
from rpy2.robjects.vectors import StrVector
# Selectively install what needs to be install.
# We are fancy, just because we can.
names_to_install = [x for x in packnames if not rpackages.isinstalled(x)]
if len(names_to_install) > 0:
utils.install_packages(StrVector(names_to_install))
importr('bootLR')
Gives error
---------------------------------------------------------------------------
RRuntimeError Traceback (most recent call last)
<ipython-input-27-359b2847dddf> in <module>
1 utils.install_packages("bootLR")
----> 2 importr('bootLR')
~/opt/anaconda3/lib/python3.7/site-packages/rpy2/robjects/packages.py in importr(name, lib_loc, robject_translations, signature_translation, suppress_messages, on_conflict, symbol_r2python, symbol_check_after, data)
451 if _package_has_namespace(rname,
452 _system_file(package = rname)):
--> 453 env = _get_namespace(rname)
454 version = _get_namespace_version(rname)[0]
455 exported_names = set(_get_namespace_exports(rname))
RRuntimeError: Error in loadNamespace(name) : there is no package called ‘bootLR’```

Python cannot import from another file name not defined

I am trying to import a custom function from another python file but keep getting an error NameError: name 'testme' is not defined. I confirmed that I am importing the file correctly according to this SO post and that the function is top level. What else can I try to fix this?
My main python file is:
import sys
import dbconn
#from dbconn import testme #<----did not work
dev=True
if(dev):
categId='528'
pollIds=[529,530,531]
else:
categId=str(sys.argv[1])
pollIds=[529,530,531]
df=testme(categIds)#callServer(categId,pollIds)
df
if(not categId.isdigit):
print('categ id fail. expected digit got: '+categId)
.....
and dbconn.py:
import pymysql #pip3 install PyMySQL
import pandas as pd
from scipy.stats.stats import pearsonr
from scipy import stats
def testme(categIds):
try:
df=categIds
except Exception as e:
print("broke")
return categIds
Not sure if it makes a difference but I am running the main python file from within a Jupyter notebook, and have a compiled version of dbconn.py in the same directory
In response to the suggestions I tried:
df=dbconn.testme(categIds)
got the error:
module 'dbconn' has no attribute 'testme'
You Have to follow these fox exact import
1)import <package>
2)import <module>
3)from <package> import <module or subpackage or object>
4)from <module> import <object>
in your case, you have tried
from dbconn import testme
you have to use only packages in from section and module in import section
like >>
from testme import dbconn

Passing python objects to R functions in rpy2

I'm working in a Jupyter notebook with Python 2 and want to use rpy2 to plot a heatmap.
import numpy as np
from rpy2 import robjects
from rpy2.robjects import r, pandas2ri
from rpy2.robjects import Formula, Environment
from rpy2.robjects.vectors import IntVector, FloatVector
from rpy2.robjects.lib import grid
from rpy2.robjects.packages import importr, data
from rpy2.rinterface import RRuntimeError
import warnings
a = np.array([1.5,2.3])
b = np.array([4.2,5.1])
c = np.array([[0.3, 0.6],[0.6, 0.3]])
r.image.plot(a,b,c)
gives me the error
AttributeError: 'SignatureTranslatedFunction' object has no attribute 'plot'
How do I properly pass the parameters into this function? Specs: rpy2 2.5.6 with R3.3.3 and Python 2.7
That doesn't work because image.plot apparently comes from the package fields. Using image from base R's graphics library, do e.g. this:
import numpy as np
from rpy2.robjects.packages import importr
from rpy2.rinterface import RRuntimeError
import rpy2.robjects.numpy2ri
from IPython.display import Image, display
from rpy2.robjects.lib import grdevices
rpy2.robjects.numpy2ri.activate()
grf = importr('graphics')
a = np.array([1.5,2.3])
b = np.array([4.2,5.1])
c = np.array([[0.3, 0.6],[0.6, 0.3]])
with grdevices.render_to_bytesio(grdevices.png, width=1024, height=896, res=150) as img:
grf.image(a, b, c)
display(Image(data=img.getvalue(), format='png', embed=True))
gives
To use image.plot, you'd have to run
fields = importr('fields')
and replace grf.image(a, b, c) with fields.image.plot(a, b, c)

To call any R package from python

Please let me know the procedure, what settings needed to call R packages from Python.
I use Spyder (python 2.7)
I am trying to call apriori package from Python.it fails in arules.
Any help would be appreciated.
I already tried the following
import rpy2
from rpy2 import *
import rpy2.interactive as r
arules = r.packages.importr("arules")
from rpy2.robjects.vectors import ListVector
od = OrderedDict()
od["supp"] = 0.0005
od["conf"] = 0.7
od["target"] = 'rules'
result = ListVector(od)
dataset = 'c:/Apriori/testcase.txt'
my_rules = arules.apriori(dataset, parameter=result)
print('my_rules',my_rules)

Rpy2 not finding package

I'm using Rpy2 on windows 7 64 and having trouble loading a package:
in R:
using(mi)
in python:
from rpy2.robjects.packages import importr
mi=importr('mi')
---------------------------------------------------------------------------
RRuntimeError Traceback (most recent call last)
<ipython-input-30-2d393a6df544> in <module>()
----> 1 mi=importr('mi')
C:\Anaconda\lib\site-packages\rpy2\robjects\packages.pyc in importr(name, lib_loc, robject_translations, signature_translation, suppress_messages, on_conflict, data)
397 if _package_has_namespace(rname,
398 _system_file(package = rname)):
--> 399 env = _get_namespace(rname)
400 version = _get_namespace_version(rname)[0]
401 exported_names = set(_get_namespace_exports(rname))
RRuntimeError: Error in loadNamespace(name) : there is no package called 'm
Any suggestions?
I had a similar problem:
rpy2.rinterface.RRuntimeError: Error in loadNamespace(name) : there is no package called speedglm
I noticed that the issue is that rpy2 does not know the location of all R libraries. In my case, typing (in R)
.libPaths()
gave me
[1] "/home/nbarjest/R/x86_64-redhat-linux-gnu-library/3.4"
[2] "/usr/lib64/R/library"
[3] "/usr/share/R/library"
While, typing (in Python 3)
import rpy2.rinterface
rpy2.rinterface.set_initoptions((b'rpy2', b'--no-save', b'--no-restore', b'--quiet'))
from rpy2.robjects.packages import importr
base = importr('base')
print(base._libPaths())
gave me only
[1] "/home/nbarjest/R/x86_64-redhat-linux-gnu-library/3.4"
I couldn't find a way to append the other two paths to base._libpath(). If you find a way to do it, please let me know. I used another workaround:
import rpy2
import rpy2.robjects as RObjects
from rpy2.robjects.packages import importr
utils = importr("utils")
d = {'print.me': 'print_dot_me', 'print_me': 'print_uscore_me'}
try:
thatpackage = importr('speedglm', robject_translations = d, lib_loc = "/home/nbarjest/R/x86_64-redhat-linux-gnu-library/3.4")
except:
try:
thatpackage = importr('speedglm', robject_translations = d, lib_loc = "/usr/lib64/R/library")
except:
thatpackage = importr('speedglm', robject_translations = d, lib_loc = "/usr/share/R/library")
This works. I hope other people who have the same problem find this useful.
For me, in importr, the argument lib_loc inside it worked, putting the first path that appears in the output of .libPaths() in R, like:
importr('name package', lib_loc="/home/nbarjest/R/x86_64-redhat-linux-gnu-library/3.4"),
where the path is the path in the output example of the #Nbarjest answer.
In python: Check the version of R being used by rpy2
import rpy2.robjects as robjects
robjects.r['version']
Check your rpy2 library location
base = importr('base')
print(base._libPaths())
In R: Check your R library location for this version of r
.libPaths()
copy the library installed in your version of r to the folder used by rpy2.
I also have this problem,and i copy the package i need to base._libPaths() ,here , and it works.
import rpy2.robjects as objects
from rpy2.robjects.packages import importer
base = importr('base')
base._libPaths()[0]
I had a similar problem. I had to uninstall R and reinstall it with admin rights, then reinstall the R package while running R with admin rights, so it would install to the standard library location (not a personal library). Then add R to the PATH variable, and reinstall rpy2.
This is was cross-posted, and answered, on the issue tracker for rpy2: https://bitbucket.org/rpy2/rpy2/issue/265/windows-error-in-loadnamespace

Categories