Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import r-packages in Python

Tags:

python

r

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.

like image 352
Juan C Avatar asked Apr 24 '26 07:04

Juan C


1 Answers

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.

like image 152
Miguel Trejo Avatar answered Apr 26 '26 20:04

Miguel Trejo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!