Section 9 Python Integration in RStudio

9.1 Setting up a python virtual environment

If you need python modules (the equivalent of R packages) that are not included in the python base modules, you will need to set up a virtual environment for reproducibility.

In order to do this successfully, you’ll need to edit the pySetup.R script so that it suits your needs. An example of this script can be found at python_setup_helps/pySetup.R.

Best practices note: you should not track your virtual environment folder in GitHub. Add the folder extension to your .gitignore file and confirm that it is not tracking the folder.

9.1.1 Python setup code snippet

This snippet checks to see if the ‘env’ folder exists - this is where the virtual environment is set up, and if it is not, it runs the pySetup.R file. If the ‘env’ folder exists, we use the {reticulate} function use_condaenv() to read the virtual environment you already created in the pySetup.R script.

library(reticulate)

if (!dir.exists("env")) {
  source("pySetup.R")
} else {
  use_condaenv(file.path(getwd(), "env"))
}

9.1.2 Editing the pySetup.R file

The things you may have to edit are the lines for the python modules you want to install in your python virtual environment (on line 6), and the version of python you want to use.

The script defaults to python version 3.8 as it seems to be the most stable for the earthengine-api module, but any version can be specified.