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?
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
@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.
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?
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, 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.