Noah Lindley
Noah Lindley

Software Developer

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"
)

Python in RStudio

šŸ’” 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!