1

I have a Python file that is part of my R project currently, named functions.py. Now I have a series of functions defined in that I would like to call. How would I pass arguments into Python when calling it from R?

It seems that if I use system('python functions.py hello world') it will call the file with arguments hello and world, but how do I then call a specific function while including further arguments?

Daniel
  • 33
  • 4
  • consider using the `reticulate` package to run python in R – Onyambu Jun 08 '22 at 02:14
  • Any suggestions on how to use it? *eye roll* – Daniel Jun 08 '22 at 03:15
  • there are many sites made just to teach you reticulate start [here](https://rstudio.github.io/reticulate/) – Onyambu Jun 08 '22 at 03:17
  • I've already gone through that, it wasn't helpful. All I gathered from that was how to use it to run entire files(without any arguments) from Python in R. – Daniel Jun 08 '22 at 03:24
  • are you working in rmarkdown or in rscript? – Onyambu Jun 08 '22 at 03:25
  • RScript, and using the shiny library – Daniel Jun 08 '22 at 03:26
  • Create a python file that contains the function call with the arguments and then run it as shown in the link – Onyambu Jun 08 '22 at 03:28
  • Or simply use `source_python` and now your functions are available in R. Run them as though you are running R function – Onyambu Jun 08 '22 at 03:30
  • I already said that I've look through the link, and I didn't see anywhere in there about how to pass arguments. – Daniel Jun 08 '22 at 03:31
  • Check where they used `source_python` – Onyambu Jun 08 '22 at 03:36
  • ```Error in file.exists(file) : object 'functions.py' not found``` Is there a way to specify to look in the same directory that the R file is contained? I'd like this to be as easy to deploy as possible. – Daniel Jun 08 '22 at 03:45
  • either give the path eg `source_python('~/path/to/file/functions.py')` if you are using windows the something like `source_python('C:/Desktop/functions.py')` etc. Or simply copy the functions.py file and paste it in the working directory folder in R – Onyambu Jun 08 '22 at 03:49
  • Ok, I've got the important pieces moving. Thanks, just gotta wrestle with Shiny now. – Daniel Jun 08 '22 at 04:39
  • Consider accepting one of the below solutions to close the question – Onyambu Jun 08 '22 at 04:40

1 Answers1

0

Here is how you can use reticulate with arguments:

your python file called greeting.py

def greetings(name,time):
    print(f'Good {time.lower()} {name.upper()}')

Now source that into R:

reticulate::source_python('greeting.py')

Now run it just the normal way you would run a R function:

greetings('Biden','evening')
Good evening BIDEN
Onyambu
  • 67,392
  • 3
  • 24
  • 53