python导入函数包,将R包中的任何函数导入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'

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值