![]() |
VOOZH | about |
In data science and machine learning, both Python and R are popular programming languages. Python is known for its simplicity and variety of libraries, while R is mostly used in statistical analysis and data visualization. Sometimes, it helps to use both Python and R in the same project to take advantage of what each language does best. Integrating Python code with R is easy, making it simple for the two to work together.
It provides several advantages such as:
There are two primary ways which are:
reticulate package in RNow we implement step by step those two methods in R programming Language.
reticulate Package in RThe {reticulate} package in R makes it easy to embed Python code within R Markdown documents, allowing us to take advantage of both languages in a single document.
reticulate PackageFirst, install the reticulate package.
Ensure that Python is properly configured.
Output:
python: C:/Python312/python.exe
libpython: C:/Python312/python312.dll
pythonhome: C:/Python312
version: 3.12.2 (tags/v3.12.2:6abddd9, Feb 6 2024, 21:26:36) [MSC v.1937 64 bit (AMD64)]
Architecture: 64bit
numpy: C:/Users/Tonmoy/AppData/Roaming/Python/Python312/site-packages/numpy
numpy_version: 1.26.4
NOTE: Python version was forced by PATH
python versions found:
C:/Python312/python.exe
C:/Users/Tonmoy/AppData/Local/Programs/Python/Python311/python.exe
C:/Users/Tonmoy/anaconda3/python.exe
Now, you can run Python code directly within your R script.
Output:
[1] 15Now import and use Python libraries like numpy in R.
Output:
[1] 1 2 3 4If there's a Python script named (script.py), it can be executed directly from R. In this example, we'll use a script that checks for Armstrong numbers, saved as am.py.
Output:
True
False
If Jupyter is not installed, you can install it using Python.
pip install jupyterTo run R code in Jupyter, you need to install the R kernel.
Open Jupyter by running the following command in your terminal or command prompt.
jupyter notebookNow we will Run the Python and R Code Together.
Python Cell
Output:
15R Cell
Output:
[1] 20Within the same notebook, we can switch between Python and R using the magic commands %%python and %%R.
Switching to R in a Python Cell:
Output:
[1] 20Switching to Python in an R Cell:
Output:
10Integrating Python code with R allows for the combination of the unique strengths of both languages, enhancing data analysis capabilities. Whether using the reticulate package in R or Jupyter Notebooks with both R and Python kernels, the process is straightforward and opens up a range of possibilities for projects. These tools enable the creation of more efficient, flexible, and collaborative workflows, leading to improved outcomes in data science tasks.