pythonrrstudioreticulate

Importing Python packages in RStudio QMD


Very new to Python and R, so apologies for probably a very basic question. Attempting to install numpy and pandas in RStudio .qmd file. I have referenced other similar questions, but I'm continuing to get the same error when I transition from R code chunks to Python code chunks.

RStudio .qmd file:

{r, warning=FALSE, output=FALSE, message=FALSE}

library(tidyverse)
library(reticulate)
py_install("numpy", pip=TRUE)
py_install("pandas", pip=TRUE)

Everything loads fine with that code. But when I change to Python after and enter this code:

{python}
import numpy as np
import pandas as pd

I get the following errors in the console:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\rober\AppData\Local\R\win-library\4.2\reticulate\python\rpytools\loader.py", line 119, in _find_and_load_hook
    return _run_hook(name, _hook)
           ^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\rober\AppData\Local\R\win-library\4.2\reticulate\python\rpytools\loader.py", line 93, in _run_hook
    module = hook()
             ^^^^^^
  File "C:\Users\rober\AppData\Local\R\win-library\4.2\reticulate\python\rpytools\loader.py", line 117, in _hook
    return _find_and_load(name, import_)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ModuleNotFoundError: No module named 'numpy'

Solution

  • I suspect you might need to set your Python environment in RStudio and make sure you py_install() into the same env (reticulate tries to auto-select one by default).

    Go to Tools -> Global Options... -> Python to see which environments are available.

    I recommend choosing r-reticulate or r-miniconda. Depending on your setup.


    Other things to try: