Search code examples
pythonrreticulate

Calling python functions in R


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?


Solution

  • 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