Calling python functions in R

Question:

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?

Asked By: Daniel

||

Answers:

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
Answered By: onyambu

@onyambu, can you give an example, where in greeting.py there is another function like this:


from multiprocessing import Pool
from os import getpid
import time

def double(i):
    print("I'm process", getpid())
    time.sleep(3)
    return i * 2 * i

def test():
    with Pool(4) as pool:
        result = pool.map(double, [1, 2, 3, 4, 5, 6, 7, 8, 9])
        print(result)

If I want to use your way, to call test() function in RStudio on Windows 10 OS, how can I do it?

I ask because I always to stuck there in RStudio, but in python by testing the function, which is ok.

Thanks.

Answered By: DavidK
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.