Ricky Robinson
Ricky Robinson

Reputation: 22933

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")

Upvotes: 4

Views: 3548

Answers (3)

lgautier
lgautier

Reputation: 11565

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

Upvotes: 8

Mohan
Mohan

Reputation: 9

   import sys,subprocess
   your_package = 'nltk' 

   package_names = subprocess.Popen([pip freeze], 
   stdout=subprocess.PIPE).communicate()[0]
   pakage = package_names.split('\n')

   for package in packages:
      if package ==your_package:
         print 'true'

Upvotes: -1

Paul Hiemstra
Paul Hiemstra

Reputation: 60984

You can use the following function I got from @SaschaEpskamp's answer to another SO post:

pkgTest <- function(x)
  {
    if (!require(x,character.only = TRUE))
    {
      install.packages(x,dep=TRUE)
        if(!require(x,character.only = TRUE)) stop("Package not found")
    }
  }

And use this instead to load your packages:

r.source("file_with_pkgTest.r")
r.pkgTest("utils")

In general, I would recommend not try to write much R code inside Python. Just create a few high-level R functions which do what you need, and use those as a minimal interface between R and Python.

Upvotes: 1

Related Questions