Python in RStudio
Using the reticulate package, you can run Python code directly within R Markdown. This makes it easy to combine the strengths of both R and Python in the same document.
š§Ŗ Running Python Code in R Markdown
With reticulate, you can embed Python chunks inside your R Markdown file and take advantage of Python librariesālike re for regular expressionsāwithout ever leaving RStudio.
Hereās an example:
```{python, python.reticulate = TRUE}
import re
example_string = """We have to extract these numbers 12, 47, 48.
The integers numbers are also interesting: 189 2036 314.
',' is a separator, so please extract these numbers 125,789,1450
and also these 564,90456. We like to offer you 7890$ per month
in order to complete this task... we are joking."""
re.findall(r'\d+', example_string)
```
Output
['12', '47', '48', '189', '2036', '314', '125', '789', '1450', '564', '90456', '7890']
š Example: Sharing Data Between Python and R
Letās create a simple dictionary in Python, then pass it to R for visualization.
š Python Code
```{python, python.reticulate = TRUE}
data = {}
for i in range(10):
data [i] = i*i
```
š R Code
# Load the reticulate package to interface with Python
library(reticulate)
# Retrieve the 'data' dictionary from Python and convert it to
# a data frame
vector <- as.data.frame(py$data)
# Transpose the data frame so values are in a single row
vector <- t(vector)
# Plot the transposed vector
plot(vector,
type = "b",
col = "blue",
pch = 16,
main = "Python Data (i * i)",
xlab = "Index",
ylab = "Value"
)
š” Final Thoughts
What makes this so useful is that you can mix R and Python in the same workflow, making it easier to solve problems using the best tools from both worlds.
Thanks for reading!

