如何使用 Rpy2 导入 Python 中的 R 包 KernSmooth?

How to import the R package KernSmooth in Python using Rpy2?

我正在使用 Python 3.7 和 rpy2 2.9.4,并在终端中使用 conda install r-kernsmooth 安装了包 r-kernsmooth (https://www.rdocumentation.org/packages/KernSmooth/versions/2.23-15) which is available in the anaconda distribution (https://docs.anaconda.com/anaconda/packages/r-language-pkg-docs/)。

当我尝试在 Python 中导入包 'r-kernsmooth' 时,出现以下错误:

import rpy2.robjects.packages as rpackages
kernsmooth = rpackages.importr('r-kernsmooth')
---------------------------------------------------------------------------
RRuntimeError                             Traceback (most recent call last)
<ipython-input-29-3b8fa4366a16> in <module>
      1 import rpy2.robjects.packages as rpackages
----> 2 utils = rpackages.importr('r-kernsmooth')

/anaconda3/lib/python3.7/site-packages/rpy2/robjects/packages.py in importr(name, lib_loc, robject_translations, signature_translation, suppress_messages, on_conflict, symbol_r2python, symbol_check_after, data)
    451     if _package_has_namespace(rname, 
    452                               _system_file(package = rname)):
--> 453         env = _get_namespace(rname)
    454         version = _get_namespace_version(rname)[0]
    455         exported_names = set(_get_namespace_exports(rname))

RRuntimeError: Error in loadNamespace(name) : there is no package called ‘r-kernsmooth’

确实,检查路径 /anaconda3/lib/python3.7/site-packages/rpy2/robjects/packages.py 没有名为 'r-kernsmooth'.

的包

我没有问题,但是,使用完全相同的过程导入包 'utils'。

我应该注意到我之前已经在 RStudio 中安装了 'KernSmooth' 并且我在那里使用它没有问题。

我的代码有问题吗?或者可能是anaconda环境被破坏了?

我找到了罪魁祸首: 似乎有一些 conda 软件包导致不一致,因此 'KernSmooth' 一开始就没有通过 anaconda 正确安装。

(base) Sebastians-MacBook-Pro:~ sebastiangsell$ conda update r-kernsmooth
Collecting package metadata: done
Solving environment: - 
The environment is inconsistent, please check the package plan carefully
The following packages are causing the inconsistency:

  - defaults/osx-64::jupyterlab_launcher==0.13.1=py37_0
  - defaults/osx-64::nbconvert==5.4.0=py37_1
  - defaults/osx-64::jupyterlab==0.35.3=py37_0
  - defaults/osx-64::jupyter==1.0.0=py37_7
  - defaults/osx-64::ipywidgets==7.4.2=py37_0
  - defaults/osx-64::notebook==5.7.4=py37_0
  - defaults/osx-64::spyder==3.3.2=py37_0
  - defaults/osx-64::jupyterlab_server==0.2.0=py37_0
  - defaults/osx-64::widgetsnbextension==3.4.2=py37_0
  - defaults/osx-64::_ipyw_jlab_nb_ext_conf==0.1.0=py37_0
  - defaults/osx-64::xlwings==0.15.1=py37_0

我关注了关于 GitHub (https://github.com/conda/conda/issues/8490) 的讨论,它指出了最新版本的 anaconda(截至 conda 4.6.9 的问题): https://github.com/conda/conda/pull/8444

通过重新安装列为不一致的软件包恢复与 anaconda 环境的一致性 解决了我的问题:

conda install package_name

希望对您有所帮助。