BookmarkSubscribeRSS Feed

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

Started 4 weeks ago by
Modified 4 weeks ago by
Views 304

PROC R makes it easy to incorporate R code within SAS programs. But what if you want to create an R script all on its own? Or, what if you want to reference an external R script within your SAS program? Keep reading to find out how!

 

This is the third post in a series of posts introducing PROC R. If interested, parts 1 and 2 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

 

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

 

Creating a Stand-Alone R Script

 

Embedding R code in a PROC R step is useful for quick analyses; however, external R scripts are often preferred for larger projects, code reuse, and collaboration. Within SAS Studio, users can create their own R scripts by selecting Program in R from the Start page, or by selecting New > R Program. This will create a .R file where you can code exclusively in R without needing to specify the PROC R step anywhere in the code.

 

01_ST_Rprogramoptions.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.

 

For example, the following R code analyzes the SASHELP.CARS data set, producing a histogram of highway miles per gallon and a table of information for Honda vehicles:

 

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

 

02_ST_highwaympg.png

 

03_ST_hondacars-1024x176.png

 

This code utilizes some of the important functions that let R and SAS speak to each other, such as sd2df() and show(); however, all code is within an R script.

 

 

Referencing an External R File Within a SAS Program

 

Users can also reference external R files within SAS programs. For example, in the previous code, I assigned Honda to the variable VMake within R. Alternatively, I could create and assign the macro variable Make in SAS, which is then passed to the R file. The edited R code also creates a new macro variable called AvgPrice that can be used in the SAS program. This code produces the same results as the previous R program.

 

New R Program (CarsAnalysisR.r)

library(tidyverse)

VMake <- symget("Make")
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))
symput("AvgPrice", avg_msrp)

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)

 

SAS Program

%let Make = Honda;

proc R infile="/innovationlab-export/innovationlab/homes/[email protected]/CarsAnalysisR.r";
run;

%put Average MSRP from R = &AvgPrice;

proc print data=filtered_cars(obs=5);
title "First 5 &Make Cars (Avg MSRP = %sysfunc(putn(&AvgPrice, dollar12.)))";
run;

04_ST_highwaympg.png

 

05_ST_hondacars-1024x176.png

 

Users can also define a fileref for a file that contains R code. Note that the fileref can be a maximum of 8 characters long.

 

General Syntax

filename script 'my_script.R'; 
proc r infile=script;

 

Edited SAS Program with a Fileref to CarsAnalysisR.r

%let Make = Honda; 

filename CarsR '/innovationlab-export/innovationlab/homes/[email protected]/CarsAnalysisR.r';

proc R infile= CarsR; 
run; 

%put Average MSRP from R = &AvgPrice; 

proc print data=filtered_cars(obs=5); 
title "First 5 &Make Cars (Avg MSRP = %sysfunc(putn(&AvgPrice, dollar12.)))";
run;

 

Conclusion

 

PROC R offers multiple ways to combine SAS and R. While embedding R code directly in a SAS program is convenient, stand-alone R scripts and external R files can make your code more modular, reusable, and easier to maintain. Whether you keep your R code inside SAS or in separate files, PROC R provides a flexible framework for integrating both languages in a single workflow.

 

 

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:
4 weeks ago
Updated by:

Viya Copilot Motion Graphic.gif

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