3

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")
Ricky Robinson
  • 21,798
  • 42
  • 129
  • 185

3 Answers3

7

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
lgautier
  • 11,363
  • 29
  • 42
  • Thanks! As for CRAN mirrors, should I just choose one from this list http://cran.r-project.org/mirrors.html? – Ricky Robinson Apr 02 '13 at 13:13
  • I think so. Without `contriburl` in the call to `install_packages()`, R is asking for interactive input about which mirror to use... and I made the guess that you'd want something completely automated (if interactive is fine, just remove `contriburl`) – lgautier Apr 02 '13 at 17:12
  • Sorry for getting back to you only now. I tried your solution, but I got this error message: `Warning message: In library(package, lib.loc = lib.loc, character.only = TRUE, logical.return = TRUE, : there is no package called ‘gtools’ Error in .Primitive("as.environment")("package:gtools") : no item called "package:gtools" on the search list` – Ricky Robinson Apr 10 '13 at 11:12
  • `File "/home/me/myProject/myProject/myScript.py", line 51, in gtools = importr_tryhard("gtools", "http://cran.cnr.Berkeley.edu") File "/home/me/myProject/myProject/myScript.py", line 42, in importr_tryhard rpack = importr(packname) File "/usr/lib/python2.7/dist-packages/rpy2/robjects/packages.py", line 117, in importr env = _as_env(rinterface.StrSexpVector(['package:'+name, ])) rpy2.rinterface.RRuntimeError: Error in .Primitive("as.environment")("package:gtools") : no item called "package:gtools" on the search list` – Ricky Robinson Apr 10 '13 at 11:12
  • I expected `importr()` to raise LibraryError. I fixed the code snippet but no time to look at this possible minor issue with exceptions now. File a bug report may be. – lgautier Apr 10 '13 at 16:16
1

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.

Community
  • 1
  • 1
Paul Hiemstra
  • 59,984
  • 12
  • 142
  • 149
  • Thanks! I am not too familiar with the conversion of R statements to Python statements. How would I write the above snippet in python? – Ricky Robinson Apr 02 '13 at 11:04
  • 1
    I am also not familiar with them, but I think the snippet I give above should work. Just save this function into a file, source the file and run it. – Paul Hiemstra Apr 02 '13 at 11:06
-1
   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'
Mohan
  • 9
  • 7
  • Could you provide some context to this code? Especially how it connects to the running R session and retrieves if a specific package has been installed. Eventhough this might work, I find the code quite hard to read. More simple and clear approaches exists, e.g. see my answer. – Paul Hiemstra Apr 02 '13 at 11:17
  • pip freeze list the all the packages you already installed in the system – Mohan Apr 02 '13 at 11:21
  • after getting the list dump into one file and split the output data based on the new line and check it.. – Mohan Apr 02 '13 at 11:23
  • 2
    We are talking about R packages from within Python, not Python packages. – Paul Hiemstra Apr 02 '13 at 11:37