Search code examples
pythonrreticulate

Problems with reticulate in R studio and importing python modules


I'm trying to run reticulate and import python modules within r studio (specifically R-markdown). The R code chunk seems to do what is expected (i.e. install the python modules) and not seem to produce any errors, but the python code chunk does not seem to do what is expected (i.e. import the installed packages). It does not produce any output (or errors) which is somewhat strange.

I've tried a fresh install of reticulate, using the devtools version of reticulate a fresh install of R Studio and using the full conda path rather than the name, but neither seem to be working. I'm at a loss to figure out what is going wrong. I've also searched stackoverflow for various answers already and have tried various suggestions, but nothing seems to be working). Additionally, I have miniconda installed and python installed as well (and python packages and scripts run perfectly fine). If anyone was able to help, that would be fantastic.

(Apologies for formatting, the last backticks indicating the end of the code chunks aren't showing up properly)

## R code chunk
```

    ```{r}
    library("reticulate")
    #devtools::install_github("rstudio/reticulate")
    conda_create("my_project_env")
    py_install(packages = c("numpy","pandas","scikit-learn","matplotlib","seaborn","statsmodels"))
    py_install(packages = c("IPython"))
    # Either of these seem to "work" for installation
    #conda_install(packages = c("numpy","pandas","scikit-learn","matplotlib","seaborn","statsmodels"))
    #conda_install(packages = c("IPython"))
    conda_list()
    use_condaenv("my_project_env")

 ```

The python code chunk below seems to "run" but does not produce any output or errors (such as the python module could not be found) and I am unable to use the modules.

## Python code chunk
```

    ```{python}

    # Main packages
    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    import seaborn as sns

```

Solution

  • It seems like the solution was to run the imports in an r studio code chunk in the following manner :

    library("reticulate")
    conda_create("my_project_env")
    py_install(packages = c("numpy","pandas","scikit-learn","matplotlib","seaborn","statsmodels"))
    conda_list()
    use_condaenv("full_path_to_python_for my_project_env")
    py_run_string('import numpy as np')
    py_run_string('import pandas as pd')
    py_run_string('import matplotlib.pyplot as plt')
    py_run_string('import seaborn as sns')
    

    From there, I was able to run the python functions in the python code chunks without issue.