R, Python: install packages on rpy2
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.
When running pytest
, Aaron's answer makes my Python hang and R keep giving error messages, probably because of this:
Calling
install_packages()
without first choosing a mirror will require the user to interactively choose a mirror.
According to rpy2 documentation, I used this which worked:
from rpy2 import robjects
import rpy2.robjects.packages as rpackages
utils = rpackages.importr('utils')
utils.chooseCRANmirror(ind=1)
utils.install_packages("DirichletReg")
DirichletReg = rpackages.importr("DirichletReg")