BookmarkSubscribeRSS Feed

Introducing PROC R (Part 4): Incorporating R Code into Flows within SAS Data and AI Studio

Started 5 hours ago by
Modified 5 hours ago by
Views 24

In this series, we have explored several ways to incorporate R code into SAS programs and create R scripts within SAS using PROC R. In this post, we'll take that integration a step further by using the R Program step in SAS Data and AI Studio flows. Flows provide a visual way to combine SAS data preparation and processing with R programming, allowing you to take advantage of the strengths of both languages within a single workflow.

 

Note: This post is based on the 2026.06 stable release of SAS Viya.

 

 

SAS Studio Flows

 

If you are asking yourself, “What is a ‘flow’?”, SAS Data and AI Studio Flows offer a low-code option for analyzing data with SAS Viya. A flow is a sequence of operations on data. Data and operations are represented in SAS Data and AI Studio by steps that you can access from the Steps section of the navigation pane. Each step in a flow is represented by a node on the flow canvas. While SAS provides several predefined steps to use in flows, users and developers also build custom steps to perform specific tasks. The R Program step is a predefined step provided by SAS; however, users can also use R code to create their own custom steps.

 

exampleflow1.pngexampleflow1.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.

 

Additional resources regarding SAS Studio Flows:

Quick Start Video

Documentation

 

 

Running the R Program Step

 

To add the R Program step to a flow, click the Steps icon in the lefthand pane. From the SAS Steps tab, expand the Develop folder and either click and drag the R Program step to the flow or right-click the step and select Add to flow.

 

rprogramstep.gifrprogramstep.gif

Users can write R code directly in the R Program step’s code editor without connecting it to other nodes in the flow. The example below uses the same R code from the previous post in this series, Introducing PROC R (Part 3): Creating and Calling R Scripts. It analyzes the SASHELP.CARS data set by creating a histogram of highway miles per gallon and a table of Honda vehicle information. To run the example, copy and paste the code into the R Program code editor and run the flow.

 

library(tidyverse)

VMake <- "Honda"
carsdf <- sd2df("sashelp.cars")

mycars <- carsdf %>%
filter(Make == VMake)

# Create a macro variable in SAS from R
avg_msrp <- round(mean(mycars$MSRP, na.rm = TRUE))

df2sd(mycars, "work.filtered_cars")

p <- ggplot(mycars, aes(x = MPG_Highway)) +
     geom_histogram(binwidth = 5, fill = "#69b3a2",
     color = "#1f3552", alpha = 0.8) +
     labs(
        title = "Distribution of Highway MPG",
        x = "Highway MPG",
        y = "Count"
        ) +
     theme_minimal(base_size = 14) +
     theme(
     plot.title = element_text(hjust = 0.5, face = "bold"),
     axis.title = element_text(face = "bold"),
     panel.grid.minor = element_blank()
)

    rplot(p)

show(head(mycars), paste0("First 5 ", VMake," Cars (Avg MSRP = ", "$", format(avg_msrp, big.mark = ","), ")")) 

 

inlinecode3-1024x488.pnginlinecode3-1024x488.png

inlinecoderesults.gifinlinecoderesults.gif

 

Node Specifications

 

From the Node tab, users can rename the step, create an external reference to the code by saving it or selecting an existing R script, and provide a description of the node.

 

nodespecs2-1024x495.pngnodespecs2-1024x495.png

 

Using the R Program Step Within a Flow

 

This example shows how to use the R Program step as part of a larger flow. SAS steps first prepare the data, and then the resulting table is passed to R for further analysis and visualization. By combining SAS and R in one flow, you can use each language where it works best—such as incorporating an existing R workflow or package into a broader SAS process without moving the entire analysis outside of SAS. In this flow, SAS prepares the HOMEEQUITY data by removing rows with missing loan or property values and calculating a loan-to-value (LTV) ratio. R then categorizes loans by LTV, creates summary statistics and a visualization with the dplyr and ggplot2 packages, and saves the enhanced data as a new SAS table.

 

homeequityflow4.pnghomeequityflow4.png

Create the flow by following these steps:

 

  1. Select New > Flow to create a new flow.
  1. Navigate to Library Connections > SASHELP > HOMEEQUITY and drag the HOMEEQUITY table to the flow.
  1. Right-click the HOMEEQUITY node and select Add a query. This automatically connects a query node the HOMEEQUITY table.

 

step1-1.gifstep1-1.gif

  1. Click the Query node and click and drag the t1 (HOMEEQUITY) table to the Select > Columns space. You can also right-click t1 (HOMEEQUITY) and select Add all columns.
  1. Navigate to the Filter tab of the Query node.
  1. Expand t1 (HOMEEQUITY) and click and drag both the LOAN and VALUE columns to the Filter tab space.
  1. Set the condition to Not Missing for both variables, and keep the Operator as AND.

 

step2.gifstep2.gif

  1. Navigate to Steps from the lefthand pane. Search for Calculate Columns.
  1. Click and drag the Calculate Columns step onto the flow.
  1. Click the output port of the Query node and drag the cursor to the input port of the Calculate Columns node to connect the two nodes together.
  1. Click the Calculate Columns node and from the Options tab select New column.

 

Untitled-Project.gifUntitled-Project.gif

  1. A new window appears to build the expression to create a new column. Here we will calculate loan-to-value ratio by dividing the LOAN column by the VALUE column. To do so, double click LOAN from the Data tab on the left side of the window, type a division sign (/), then double-click VALUE from the Data tab.
  1. Change the column name to LTV and the column label to Loan-to-Value Ratio.
  1. Change the Type to Numeric. Click Save.

 

Untitled-Project2.gifUntitled-Project2.gif

  1. Navigate to Steps from the lefthand pane. Search for Table.
  1. Click and drag the Table node to the flow and connect the output port of the Calculate Columns node to the Table node.
  1. Select the Table node and set the library to WORK and the table name to HOMEEQUITY_SAS.

 

step-4.gifstep-4.gif

  1. Navigate to Steps from the lefthand pane. Search for R Program.
  1. Click and drag the R Program step to the flow, then connect the HOMEEQUITY_SAS node to the input port of the R Program node. To create the connection, hover over the right side of the HOMEEQUITY_SAS node until the cursor changes to a pointing hand. Click and drag from this location to the input port of the R Program node.
  1. The following R code creates a new column called LTV_Category which categorizes Loans as having a Low, Medium, or High LTV ratio. The code also creates a summary table for the LTV category and a scatterplot of loan amount versus property value by LTV category. It also converts the R data frame into a SAS data frame called HOMEEQUITY_LTV. Select the R Program step and paste the code into the R code editor:
library(dplyr)
library(ggplot2)

homeequity <- sd2df("HOMEEQUITY_SAS")

# Create an LTV category
homeequity <- homeequity %>%
  mutate(
    LTV_Category = case_when(
      LTV < 0.5 ~ "Low",
      LTV < 0.8 ~ "Medium",
      TRUE ~ "High"
    )
  )

# Create a summary table by LTV category
loan_summary <- homeequity %>%
  group_by(LTV_Category) %>%
  summarise(
    Number_of_Loans = n(),
    Average_Loan = mean(LOAN, na.rm = TRUE),
    Average_Value = mean(VALUE, na.rm = TRUE),
    Average_LTV = mean(LTV, na.rm = TRUE),
    .groups = "drop"
  )

# Create a scatter plot showing loan amount
# versus property value by LTV category
ltv_plot <- ggplot(
  homeequity,
  aes(
    x = VALUE,
    y = LOAN,
    color = LTV_Category
  )
) +
  geom_point(
    alpha = 0.65,
    size = 2
  ) +
  geom_smooth(
    method = "lm",
    se = FALSE,
    linewidth = 1.1
  ) +
  scale_color_manual(
    values = c(
      "Low" = "#4C78A8",
      "Medium" = "#F2A541",
      "High" = "#D95F59"
    )
  ) +
  scale_x_continuous(
    labels = scales::label_dollar()
  ) +
  scale_y_continuous(
    labels = scales::label_dollar()
  ) +
  labs(
    title = "Home Equity Loans by Loan-to-Value Category",
    subtitle = "Relationship between property value and loan amount",
    x = "Property Value",
    y = "Loan Amount",
    color = "LTV Category"
  ) +
  theme_minimal(base_size = 12) +
  theme(
    plot.title = element_text(
      face = "bold",
      size = 16
    ),
    plot.subtitle = element_text(
      size = 11,
      margin = margin(b = 15)
    ),
    axis.title = element_text(
      face = "bold"
    ),
    legend.title = element_text(
      face = "bold"
    ),
    panel.grid.minor = element_blank(),
    panel.grid.major.x = element_blank(),
    plot.title.position = "plot"
  )

# Convert homeequity table from R data frame to SAS table
df2sd(homeequity, "HOMEEQUITY_LTV")

# Display the outputs
show(loan_summary)

rplot(ltv_plot)

 

step-5.gifstep-5.gif

  1. Run the flow and select Submitted Code and Results.
  1. From the Results tab, you can view the summary table and scatter plot generated by R. The Output Data tab contains the HOMEEQUITY_LTV table created by the R Program step, which includes the new LTV_Category column and can be used in subsequent steps or analyses.

 

resultsR.gifresultsR.gif

 

Conclusion

 

The R Program step extends SAS Data and AI Studio flows by making it easier to bring R into a visual SAS workflow. In this example, SAS steps prepared the data, R performed additional analysis and visualization, and the results were returned to SAS for continued use. This approach lets you use R where it adds value while keeping the overall process organized and reusable within SAS.

 

 

Previous Posts in Series

 

This is the fourth post in a series of posts introducing PROC R. If interested, parts 1, 2, and 3 can be found here:

 

Part 1: Introducing PROC R (Part 1): The Newest Way to Integrate R and SAS

 

Part 2: Introducing PROC R (Part 2): Creating R Plots Within SAS Programs

 

Part 3: Introducing PROC R (Part 3): Creating and Calling R Scripts

 

Note: To access PROC R, users should have access to SAS Viya 2026.03 or later.

 

 

Helpful Links

 

Introducing PROC R Video

 

SAS PROC R Deep Dive Video

 

PROC R Documentation

 

 

Find more articles from SAS Global Enablement and Learning here.

Contributors
Version history
Last update:
5 hours ago
Updated by:

Viya Copilot Motion Graphic.gifViya Copilot Motion Graphic

Ready to see what SAS Viya Copilot can do?

Visit the Tips & Tricks page for setup guidance, demos, and practical examples that show how Copilot supports your workflows.

Get Started →

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