Search code examples
pythonrrpy2bnlearn

Importing any function from an R package into python


While using the rpy2 library of Python to work with R. I get the following error message while trying to import a function of the bnlearn package:

# Using R inside python
import rpy2
import rpy2.robjects as robjects
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 = ('visNetwork', 'bnlearn')
utils.install_packages(StrVector(packnames))

# Load packages
visNetwork = importr('visNetwork')
bnlearn = importr('bnlearn')

tabu = bnlearn.tabu
fit = bn.learn.bn.fit

With the error:

AttributeError: module 'bnlearn' has no attribute 'bn'

Solution

  • While checking the bnlearn documentation one finds out that bn is a class structure. So one should check out all the attributes of the object in question, that is, running:

    bnlearn.__dict__['_rpy2r']
    

    After that you should get a similar output like the next one, where you find how you would import each attribute of bnlearn:

    ...
    ...
    'bn_boot': 'bn.boot',
      'bn_cv': 'bn.cv',
      'bn_cv_algorithm': 'bn.cv.algorithm',
      'bn_cv_structure': 'bn.cv.structure',
      'bn_fit': 'bn.fit',
      'bn_fit_backend': 'bn.fit.backend',
      'bn_fit_backend_continuous': 'bn.fit.backend.continuous',
      'bn_fit_backend_discrete': 'bn.fit.backend.discrete',
      'bn_fit_backend_mixedcg': 'bn.fit.backend.mixedcg',
      'bn_fit_barchart': 'bn.fit.barchart',
      'bn_fit_dotplot': 'bn.fit.dotplot',
    ...
    ...
    

    Then, running the following will solve the issue:

    bn_fit = bnlearn.bn_fit
    

    Now, you could, for example, run a bayesian Network:

    structure = tabu(datos, score = "loglik-g")
    bn_mod = bn_fit(structure, data = datos, method = "mle")
    

    In general, this approach solves the issue of importing any function from an R package into Python through the rpy2 package.