In data science and analytics, professionals often work with many tools and languages to harness the full potential of their projects. Integrating Python and R becomes very helpful when dealing with data manipulation, analysis, and visualization capabilities.
There is more than one method to call Python from R:
We can use the retuculate
package.
We can use the system
function.
reticulate
packageThe reticulate
package can be used as a bridge between R and Python. It allows us to run the Python code from the R scripts, and interact with Python very easily. We can install this package using the following command:
install.packages("reticulate")
Note: We have already installed this package in the playground below. To install it on your local system, run the R console and then run the above command in the R console.
We can use the reticulate
package to import Python modules, call Python functions, and even pass data back and forth between R and Python.
The example below uses the reticulate package to interact with Python code:
def mul(x, y): return x * y
The example above used two approaches to run Python:
Import the Python math
library and use it inside the R code (lines 5 and 8).
Run the Python Script.py
file (lines 13 and 14).
system
functionThe R code provides the system
functions. These functions allow us to execute the system
commands, as well as Python scripts. This method is useful when executing Python scripts from R code. For example:
system("python3 script.py agr1 arg2 and so on..")
python3
: This is the command used to run the Python file.
script.py
: This is the file name that has the Python code.
arg1
, arg2
: These are the argument that we can pass to the Python code.
The example below uses the system
functions to interact with Python code:
import sys print(f'Hello {sys.argv[1]}!!!!!') print("The sum of two numbers is: ",int(sys.argv[2])+int(sys.argv[3]))
In the my_pythonScript.py
file, we print the "Hello"
message with the first command-line argument on line 2. In the next line, we calculate and print the sum of the second and third command-line arguments as an integer and a message.
Free Resources