rpy2找不到已安装的外部R包

时间:2015-10-07 03:34:19

标签: python r rpy2

我之前(约1年前)已完成此操作,但想通过rpy2再次使用R.我已经确认我可以在执行此操作时加载默认包:

from rpy2 import robjects
plot = robjects.r.get('plot')

现在,当我尝试加载这样的外部包时,

from rpy2.robjects.packages import importr
betareg = importr('betareg')

我收到以下错误:

Traceback (most recent call last):

  File "<ipython-input-1-b1ed20534ab9>", line 1, in <module>
    runfile('C:/Users/Patrick/OneDrive/FIDS/betareg.py', wdir='C:/Users/Patrick/OneDrive/FIDS')

  File "C:\Anaconda\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 685, in runfile
    execfile(filename, namespace)

  File "C:\Anaconda\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 71, in execfile
    exec(compile(scripttext, filename, 'exec'), glob, loc)

  File "C:/Users/Patrick/OneDrive/FIDS/betareg.py", line 11, in <module>
    betareg = importr('betareg')

  File "C:\Anaconda\lib\site-packages\rpy2\robjects\packages.py", line 438, in importr
    env = _get_namespace(rname)

RRuntimeError: Error in loadNamespace(name) : there is no package called 'betareg'

我设置了R_HOMER_USERR_LIBS个系统变量,以确保R被加载并且(希望)指向外部包所在的位置。当我在lib_loc中设置importr kwarg作为包文件夹的路径时,也会发生同样的事情。我可以通过命令行中的library('betareg')加载包,其中包含r2py正在使用的相同运行参数(--quiet, - no-save)。

我在这里遗漏了什么?如何设置以便我可以加载已安装的外部包?

版本信息

OS:

Microsoft Windows [Version 10.0.10240]

Python版本:

Python 2.7.10 |Anaconda 2.3.0 (64-bit)| (default, May 28 2015, 16:44:52)
[MSC v.1500 64 bit (AMD64)] on win32

R版:

R version 3.2.0 (2015-04-16) -- "Full of Ingredients"
Copyright (C) 2015 The R Foundation for Statistical Computing
Platform: x86_64-w64-mingw32/x64 (64-bit)

rpy2版本:

>>>import rpy2
>>> rpy2.__version__
'2.6.3'

1 个答案:

答案 0 :(得分:3)

要在Conda中使用外部R软件包,您将在Conda中安装这些软件包。如果您从R安装它们,则无法使用它们。要安装(例如对于dtw库),接下来要做:

import rpy2.robjects.packages as r
utils = r.importr("utils")
package_name = "dtw"
utils.install_packages(package_name)

输出是:

rpy2.rinterface.NULL

然后你可以使用这个包

import rpy2.robjects.numpy2ri
from rpy2.robjects.packages import importr
rpy2.robjects.numpy2ri.activate()

# Set up our R namespaces
R = rpy2.robjects.r

DTW = importr('dtw')   # our package