Best way to use a conda environment with source_python

What is the best way to call a specific conda environment when using source_python in R code to call Python.

I have this Python script where I define a small function.

import xarray as xr
import os

def open_dscim_econ_vars(ssp_in, model_in, year_list, econ_vars, 
path_in='/mnt/battuta_shares/gcp/integration_replication/inputs/econ/raw/integration-econ-bc39.zarr'):
    
    econ_var_data = xr.open_zarr(path_in)
    
    econ_var_out = (econ_var_data[[econ_vars]]
                    .sel(ssp = ssp_in, model = model_in, year = year_list)
                    .to_dataframe()) 
                    
    econ_var_out.reset_index(inplace = True)
                    
    return econ_var_out

Then in my R code I use source_python to call the function open_dscim_econ_vars

source_python("~/repos/inequality/python_functions/get_dscim_econ_vars.py")
econ_vars_raw = open_dscim_econ_vars(ssp_in ='SSP3', model_in = 'low', year_list =c(2015, 2099),
                                       econ_vars ='gdp')

I have a conda environment I already made via reticulate::conda_create() called r-reticulate-ineq and I would like to make sure that when open_dscim_econ_vars() is called it is inside this environment. What is the best way to load the conda environment.

Should I just modify my R script to be something like this?

source_python("~/repos/inequality/python_functions/get_dscim_econ_vars.py")
use_condaenv('r-reticulate-ineq')
econ_vars_raw = open_dscim_econ_vars(ssp_in ='SSP3', model_in = 'low', year_list =c(2015, 2099),
                                       econ_vars ='gdp')

Or will that not work and I should do something else?

I think you need to call use_condaenv() prior to source_python(). In other words, you need to tell {reticulate} which Python executable you want to use as your Python interpreter before you have it parse Python code you have written in a file.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.