Setup a virtual Python environment for RStudio

Sometimes there are more than one version of python installed on the computer, and it is not obvious to identify which one is being used by default especially when using another language environment. Thus, it may be the situation that certain packages needed for one project are not needed for others, or the required packages are not installed in the target python environment. So it is better that one project or one type of projects has its own python environment. Anaconda has good environment control system if the project is in python. But if one needs work in another language environment, for example, R studio for many bioinformatics or other types of data analysis projects, with link to python, it is another situation.

Here are the steps to setup a new virtual python environment for projects in R studio by using reticulate:

 

1. Install python (official website or Anaconda) to computer

 

2. Install virtualenv package

open terminal:

pip install virtualenv

 

3. Create new python environment for project

open terminal and:

  • relocate to the project folder:

    cd <path>

  • create new virtual environment:

    virtualenv <env_name>

  • should see a new folder named env_name

 

4. Activate python environment

open terminal:

source <env_name>/bin/activate

 

5. Install packages to this new environment

open terminal:

pip install numpy tensorflow …

 

6. Use this new Python environment in R

  • install reticulate in R console:

    1
    install.packages("reticulate")
  • configure reticulate:

    create new file called “.Renviron“ under the project path,
    then put: RETICULATE_PYTHON=<env_name>/bin/python in the file.

 

7. Restart R

verify if the reticulate is correctly configured:

R console:

1
reticulate::py_config()