将R包中的任何函数导入python [英] Importing any function from an R package into python

查看:297
本文介绍了将R包中的任何函数导入python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Python的rpy2库与R配合使用时,在尝试导入bnlearn软件包的功能时收到以下错误消息:

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

出现错误:

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

推荐答案

在检查bnlearn时文档人们发现 bn是一个阶级结构.因此,应该检查出该对象的所有属性,即运行:

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']

在那之后,您将获得与下一个类似的输出,在该输出中,您将找到如何导入bnlearn的每个属性:

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',
...
...

然后,运行以下内容将解决此问题:

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

通常,这种方法解决了通过rpy2包将R包中的任何函数导入Python的问题.

这篇关于将R包中的任何函数导入python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆