Developers using SAS Viya Workbench can now take advantage of full R programming capabilities—whether that means writing R scripts, R Markdown files, or working in Jupyter Notebooks. R is well-known for its robust statistical functions, powerful visualization libraries, and flexible data wrangling tools.
Each programming language has its strengths and weaknesses, and often times we want to use multiple languages within a single workflow. For example, you might be building an R workflow but need to leverage a Python library for predictive modeling. The reticulate package makes this possible by allowing you to run Python code directly within an R environment.
In this post, we’ll explore several ways to execute Python code within an R workflow using reticulate, including:
Importing Python modules into R
Running Python code snippets
Sourcing external Python scripts
Running Python code within an R terminal
Start your workbench by choosing the programming interface you prefer by selecting either Launch Jupyter Lab - Python and R or Launch VS Code - SAS and R. Both interfaces allow users to create R scripts and Jupyter Notebooks, however only VS code allows users to create R Markdown files.
Select any image to see a larger version.
Mobile users: To view the images, select the "Full" version at the bottom of the page.
This demo will be conducted in Visual Studio Code (VS Code) using a Jupyter Notebook configured with an R kernel.
If the reticulate package is not installed, simply run the following code to install it. Once the package is installed, delete this line of code since the package only needs to be installed once.
install.packages("reticulate")
Next, open a terminal window within SAS Viya Workbench and run the following code:
which python3
This returns the location of the Python executable that we want the reticulate package to use.
This is especially important if:
You installed packages like pandas or numpy
You want consistency across R sessions or projects
library(reticulate)
use_python("copied output from terminal")
py_config()
# Import the Python 'os' module
os <- import("os")
# Use a function from the imported module
os$getcwd() # Gets the current working directory from Python
# Run a simple Python script
py_run_string("
import pandas as pd
data = {'a': [1, 2, 3], 'b': [4, 5, 6]}
df = pd.DataFrame(data)
")
# Access the dataframe from R via the 'py' object
py$df
# my_analysis.py
def scale_values(x, scale_factor):
return [i * scale_factor for i in x]
def summarize_data(data):
return {"mean": sum(data)/len(data)}
Then, in the Jupyter Notebook, include the following code. The source_python() function from the reticulate package makes the functions and variables from the Python script available directly in the R environment.
# Source the Python script
source_python("myanalysis.py")
# Call the Python functions directly from R
my_data <- c(1, 2, 3, 4)
scaled_data <- scale_values(my_data, 10)
summary <- summarize_data(my_data)
print(scaled_data)
print(summary)
library(reticulate)
repl_python()
d = {"apple": 3, "banana": 5}
print(d["banana"])
When creating an R Markdown file, users have the ability to create Python chunks within the file. For example, in the output below, the first few chunks run R code while the last chunk runs Python code.
Code:
Learn more about using R in SAS Viya Workbench here: Getting Started with R in SAS Viya Workbench
For step-by-step instructions to start a workbench instance visit SAS Tutorial | Getting Started with SAS Viya Workbench for Learners.
Students and educators can access SAS Viya Workbench for Learners for free: SAS Viya Workbench for Learners | SAS
Find more articles from SAS Global Enablement and Learning here.
It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.
The rapid growth of AI technologies is driving an AI skills gap and demand for AI talent. Ready to grow your AI literacy? SAS offers free ways to get started for beginners, business leaders, and analytics professionals of all skill levels. Your future self will thank you.