BookmarkSubscribeRSS Feed

Integrating Python Code into R Workbooks in SAS Viya Workbench

Started ‎09-08-2025 by
Modified ‎09-08-2025 by
Views 170

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

 

  • Adding Python chunks to R Markdown files

 

 

Setting Up Your Environment:

 

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.

 

01_ST_ret1.png

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.

 

02_ST_ret2.png

 

 

Installation and Loading

 

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

 
03_ST_ret5.png

 

Copy the output and run the following code. This code loads the reticulate package, specifies the python version that reticulate should use, and outputs the Python configuration for confirmation.
 
library(reticulate)
use_python("copied output from terminal")
py_config()

 

Here's what the code cell would look like:
 
04_ST_ret4-1024x298.png

 

Now that the reticulate package is loaded and able to connect to Python, let's talk about how to use it.

 

 

Method 1: Import Python Modules

 

One way to use Python with reticulate is to import Python modules for the analysis. The import() function brings a Python module into your R session as an R object. You can then access its functions and attributes using the dollar sign $ operator. For example, say I wanted to use Python's os module. I would first import the module, then use a function from the module like so:
 
# Import the Python 'os' module
os <- import("os")

# Use a function from the imported module
os$getcwd() # Gets the current working directory from Python

 

05_ST_ret6-1024x165.png

 

 

Method 2: Run Python Code from a String

 

For quick, one-off commands or short code snippets, you can use py_run_string() to execute Python code contained within an R string. The code runs in the main Python environment, and any variables created can be accessed through the py object.
 
# 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
 
06_ST_ret7-1024x369.png

 

 

Method 3: Source a Python script

 

Another way to integrate Python into an R workflow is by sourcing an external Python script. The reticulate function source_python() makes this simple by loading the script into your R session.
 
Example:
 
First, create a Python file named my_analysis.py with the following content. This Python program defines two functions, scale_values() and summarize_data(). scale_values() multiples each data value in x by the scale_factor value. summarize_data() calculates the mean of the data values provided.
 
# 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)}

 

07_ST_ret12.png

 

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)

 

08_ST_ret11-1024x324.png

 

 

Method 4: Use the interactive Python REPL

 

For interactive exploration, reticulate can launch an embedded Python REPL (Read-Eval-Print Loop) directly within an R terminal. This lets you experiment with Python syntax on the fly.
To open an R terminal, from the bottom half of the interface, select the plus sign + > R Terminal.
 
09_ST_ret10-1024x255.png

 

From the terminal, users can run repl_python(). When you run this code, the output will switch to a Python prompt (>>>). You can then run Python code directly. For example, a user could run the following within the R terminal:
 
library(reticulate)
repl_python()
d = {"apple": 3, "banana": 5}
print(d["banana"])
 
10_ST_ret8.png

 

 Type exit and press Enter to return to the R session.
 

 

Method 5: Creating Python Chunks in an R Markdown File

 

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:
 
11_ST_ret14.png

 

Resulting Knitted File:
 
12_ST_ret15.png

 

 

Conclusion

 

The reticulate package gives you the flexibility to combine the strengths of R and Python into a single file, and SAS Viya Workbench is the ideal environment to create such a file.
For general information about SAS Viya Workbench visit SAS Viya Workbench | SAS

 

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.

Contributors
Version history
Last update:
‎09-08-2025 11:45 AM
Updated by:

hackathon24-white-horiz.png

The 2025 SAS Hackathon has begun!

It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.

Latest Updates

SAS AI and Machine Learning Courses

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.

Get started

Article Tags