Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rpy2: check if package is installed

Using rpy2, I want to check if a given package is installed. If it is, I import it. If not, I install it first.

How do I check if it's installed?

from rpy2 import *
if not *my package is installed*:
   rpy2.interactive as r
   r.importr("utils")
   package_name = "my_package"
   r.packages.utils.install_packages(package_name)
myPackage = importr("my_package")
like image 461
Ricky Robinson Avatar asked Oct 17 '25 06:10

Ricky Robinson


1 Answers

Here is a function that'd do it on the Python side (note the contriburl, that should be set to a CRAN mirror, and that the case where installing the library is failing is not handled).

from rpy2.rinterface import RRuntimeError
from rpy2.robjects.packages import importr
utils = importr('utils')

def importr_tryhard(packname, contriburl):
    try:
        rpack = importr(packname)
    except RRuntimeError:
        utils.install_packages(packname, contriburl = contriburl)
        rpack = importr(packname)
    return rpack
like image 155
lgautier Avatar answered Oct 19 '25 20:10

lgautier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!