0

I am building a R package that uses a Python script which in turn loads internal data. Both the py-script (load_csv.py) as well as the data (data.csv) are located in the inst/ folder of the package directory.

import pandas as pd
my_df = pd.read_csv("inst/data.csv")

The idea is to run the py-script when a R-function (rfunction) is called:

rfunction <- function() {
          reticulate::py_run_file(system.file("load_csv.py", package = "mypkg"))
}

After building the package and calling the r-function rfunction() I get the following error:

Error: FileNotFoundError: [Errno 2] No such file or directory: 'inst/data.csv'

How can I resolve this error? Is there maybe a system call that I can place within the py-script (analogous to system.file in R)?

Ben Nutzer
  • 1,082
  • 7
  • 15

1 Answers1

1

I don't know much about R, but I'm guessing this is caused by the python script not being executed in the expected directory.

I'm assuming your python file is located in the inst folder of your package. As a quick and dirty solution, you could try to get around this by modifying your script to something like

import os
import pandas as pd 

datafile = os.sep.join((
    os.path.dirname(__file__), # this gives the directory in which the python file is located, i.e. <package>/inst/
    "data.csv"
))

my_df = pd.read_csv(datafile)
Hoodlum
  • 950
  • 2
  • 13
  • Thanks for taking the time to answer. I tried your code but the error persists. It might be that the path needs to be communicated to R as well somehow (like in this [answer](https://community.rstudio.com/t/how-to-source-a-python-file-that-imports-another-python-file-using-reticulate-in-an-r-package/156904)). – Ben Nutzer Apr 26 '23 at 08:14
  • 1
    I may have made a bad assumption in thinking that the python file was in the root of your package. You might need to correct that (I'll edit the answer if it's the case). Have a look at the path in the error message. Does it contain a double `inst` ? – Hoodlum Apr 26 '23 at 09:21
  • You are a genius, thank you very much! I removed the "inst" line from your code and it works. – Ben Nutzer Apr 26 '23 at 09:49
  • happy to help! :) I've updated the answer to reflect the fact that the python script is located in `inst` – Hoodlum Apr 26 '23 at 10:17