I'm using R
in my Python script through the rpy2
library and I need a package that is not in the default installation of R. How can I install it?
install.packages("DirichletReg", repos="http://r-forge.r-project.org")
won't work.
On Python:
>>> install.packages("DirichletReg", repos="http://r-forge.r-project.org")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'install' is not defined
And from R:
> install.packages("DirichletReg", repos="http://r-forge.r-project.org")
Installing package(s) into ‘/usr/local/lib/R/site-library’
(as ‘lib’ is unspecified)
Warning message:
In getDependencies(pkgs, dependencies, available, lib) :
package ‘DirichletReg’ is not available (for R version 2.14.1)
rpy2 will typically require an R version that is not much older than itself. This means that even if your system has R pre-installed, there is a chance that the version is too old to be compaible with rpy2. At the time of this writing, the latest rpy2 version is 2.8 and requires R 3.2 or higher.
Getting started. The rpy2 Python package will perform the magic that allows us to use R packages in our Python session. The importr function give us the power to import R packages and pandas2ri —along with the subsequent pandas2ri.
Ricardo's answer no longer works.
To install from Python, we can use the utils.install_packages
function:
from rpy2.robjects.packages import importr
utils = importr('utils')
(That utils
package is the R.utils
package whose pdf documentation can be found here: https://CRAN.R-project.org/package=R.utils - or, more directly here, is the more verbose install.packages
function documentation that we use: https://www.rdocumentation.org/packages/utils/versions/3.6.2/topics/install.packages. It is renamed to install_packages
in Python because the .
is not part of a legal Python name as it is in R.)
Next, you need to decide which repo to get the package from.
You can declare the repo when calling utils.install_packages
with the repos
argument:
utils.install_packages('DirichletReg', repos="https://cloud.r-project.org")
Or you can set the mirror before calling utils.install_packages
with
utils.chooseCRANmirror(ind=1) # select the first mirror in the list
or
utils.chooseBioCmirror(ind=1) # select the first mirror in the list
otherwise Python/R will attempt to launch the interactive mirror selector (which may or may not work with your setup).
And then, for a single package:
utils.install_packages('DirichletReg')
Or for multiple packages, pass it a character vector:
from rpy2.robjects.vectors import StrVector
package_names = ('ggplot2', 'hexbin')
utils.install_packages(StrVector(package_names))
These examples were adapted from the rpy2 documentation and the install.packages
documentation - and as of my last edit, the documentation still says to do this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With