rpy2: load R version installed in conda environment, not the one in the system

Viewed 666

I'm using rpy2 to run some R code from within a Python script. The script is run from within a conda environment which contains R version 3.6.1 installed.

The problem is that when I run the script rpy2 loads the R installed in the system (i.e., not in the environment) which is an older version 3.4.4. I check the loaded version like this:

from rpy2.robjects import r
r("""cat(paste("R version: ",R.version.string))""")

How can I force rpy2 to use the R version installed in the conda environment?


Add

I removed the system's version of R, and now trying to run the above lines results in:

ValueError: r_home is None. Try python -m rpy2.situation

Running python -m rpy2.situation which shows this:

rpy2 version:
3.3.5
Python version:
3.8.3 (default, Jul  2 2020, 16:21:59) 
[GCC 7.3.0]
Looking for R's HOME:
    Environment variable R_HOME: None
    Calling `R RHOME`: /home/gabriel/miniconda3/envs/py3/lib/R
    Environment variable R_LIBS_USER: None
R's additions to LD_LIBRARY_PATH:

R version:
    In the PATH: R version 3.6.1 (2019-07-05) -- "Action of the Toes"
    Loading R library from rpy2: OK
Additional directories to load R packages from:
None
C extension compilation:
  include:
  ['/home/gabriel/miniconda3/envs/py3/lib/R/include']
  libraries:
  ['R', 'pcre', 'lzma', 'bz2', 'z', 'rt', 'dl', 'm', 'icuuc', 'icui18n']
  library_dirs:
  ['/home/gabriel/miniconda3/envs/py3/lib', '/home/gabriel/miniconda3/envs/py3/lib', '/home/gabriel/miniconda3/envs/py3/lib/R/lib']
  extra_compile_args:
  []
  extra_link_args:
  ['-Wl,--export-dynamic', '-fopenmp', '-Wl,-O2', '-Wl,--sort-common', '-Wl,--as-needed', '-Wl,-z,relro', '-Wl,-z,now', '-Wl,--disable-new-dtags', '-Wl,--gc-sections', '-Wl,-rpath,/home/gabriel/miniconda3/envs/py3/lib', '-Wl,-rpath-link,/home/gabriel/miniconda3/envs/py3/lib', '-Wl,-rpath-link,/home/gabriel/miniconda3/envs/py3/lib']

which would appear to show that rpy2 is aware of the R installed in conda.

1 Answers

If I remember correctly, the link to the R installation to use is made during the installation of rpy2.

To use the specific R installation you mentionned I guess you can do the following steps:

  • uninstalling rpy2
  • adding the bin folder of the R installation targeted in the PATH environnement variable :
    export PATH=${PATH}:/path/to/conda/R-3.6.1/bin/
  • setting the R_HOME variable environnement to the folder of the R installation targeted: export R_HOME=/path/to/conda/R-3.6.1/
  • installing rpy2 again.
Related