Juan C
Juan C

Reputation: 6132

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. I installed this version: https://anaconda.org/conda-forge/r-hunspell, but I'm not being able to import it. Is this package supposed to work with Python? Should I use rpy2 to import it? 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.

I also noticed that this package, also installed an r-base package, but I'm also not sure how to import that.

Upvotes: 10

Views: 17062

Answers (1)

Miguel Trejo
Miguel Trejo

Reputation: 6667

After running in the command line:

pip install rpy2

or with the "!" if you're in a 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.

Upvotes: 13

Related Questions