简体   繁体   English

如何在 Python 中导入 r-packages

[英]How to import r-packages in Python

I'm a bit troubled with a simple thing.我对一件简单的事情有点烦恼。 I was trying to install a package called hunspell, but I discovered it is originally an R package.我试图安装一个名为 hunspell 的包,但我发现它最初是一个 R 包。 I installed this version: https://anaconda.org/conda-forge/r-hunspell , but I'm not being able to import it.我安装了这个版本: https ://anaconda.org/conda-forge/r-hunspell ,但我无法导入它。 Is this package supposed to work with Python?这个包应该与 Python 一起工作吗? Should I use rpy2 to import it?我应该使用rpy2导入它吗? First time using cross-platform packages so I'm a bit confused.第一次使用跨平台包所以我有点困惑。

Just to be clear, import hunspell brings ModuleNotFoundError: No module named 'hunspell' and import r-hunspell brings SyntaxError: invalid syntax .需要明确的是, import hunspell带来ModuleNotFoundError: No module named 'hunspell'import r-hunspell带来SyntaxError: invalid syntax

I also noticed that this package, also installed an r-base package, but I'm also not sure how to import that.我还注意到这个包,还安装了一个r-base包,但我也不确定如何导入它。

After running in the command line:在命令行运行后:

pip install rpy2

or with the "."或者用“。” if you're in a Jupyter Notebook.如果你在 Jupyter Notebook 中。 The following procedure will answer your issue , based on the official documentation :根据官方 文档以下过程将回答您的问题

# Using R inside python
import rpy2
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 = ('hunspell', 'some other desired packages')
utils.install_packages(StrVector(packnames))

# Load packages
hunspell = importr('hunspell')

If you want to access specific functions in this module you could check out these answer or that answer too.如果您想访问此模块中的特定功能,您也可以查看这些答案或那个答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM