Skip to content
sol-engPublic

About

R package for working with SAS Viya

Resources

Stars

2 stars

Watchers

0 watching

Forks

Latest commit

 

History

123 Commits

Folders and files

Repository files navigation

viyar hex logo

Work with SAS Viya from R

viyar addresses the missing piece in the R – SAS Viya integration:

CAS Compute (SAS code, PROCs) Runtime deps
swat (R) yes no R
saspy via Compute Session yes Python
sasr via saspy yes Python + reticulate
viyar via Compute Session yes R

Quick start

Inside Posit Workbench

If Workbench has a Viya OAuth integration configured, viyar auto-detects both the token and the Viya server URL — getting a session is one line, no viya_config() or login step needed:

library(viyar)
h <- viya_session()
viya_librefs(h)

Anywhere else (local desktop R, Posit Connect, CI)

viya_config(url = "https://your-viya-server.example.com")
# token: VIYA_TOKEN env var, or viya_login() for an interactive SSO login

h <- viya_session()                    # compute session (retry/reachability aware)
viya_librefs(h)
r <- viya_submit(h, "cas m; caslib _all_ assign;")
viya_librefs(h)                        # now includes PUBLIC, CASUSER, ...

heart <- viya_read(h, "PUBLIC", "HEART")     # SAS/CAS -> R
adsl  <- viya_read(h, "WORK", "ADSL", dates = "TRTSDT")  # SAS dates -> Date
viya_write(h, subset(heart, Cholesterol > 300), "WORK", "HIGH_CHOL")

viya_caslib_tables(h, "Public")        # loaded / unloaded states
viya_caslib_files(h, "Public")         # source files on disk
viya_load_table(h, "Public", "orders.sashdat", promote = TRUE)

viya_upload(h, "report.html", "/Public")
viya_end(h)

Submitting SAS code

viya_submit() returns the log by default. Ask for the listing (LST text) or the ODS HTML with output:

r <- viya_submit(h, code, output = c("log", "listing", "html"))
r$log        # character vector of log lines
r$listing    # character vector of listing lines
r$html       # character vector of HTML documents, named by ODS object

Each kind costs extra requests, so viyar fetches only what you ask for. The default, output = "log", behaves as before.

viyar does not add ODS statements to your code. A destination produces output only when your own code opens it, and a compute server starts with ods listing closed:

r <- viya_submit(h, "ods listing;
                     proc print data=sashelp.class(obs=5); run;
                     ods listing close;",
                 output = "listing")
cat(r$listing, sep = "\n")

For HTML, open an html5 destination with no file=. The compute server then routes the output to its results endpoint, where viyar can download it. Giving it an explicit file= writes to the compute server's own disk instead, where the results endpoint never sees it:

r <- viya_submit(h, "ods html5(id=viyar);
                     proc means data=sashelp.class; run;
                     ods html5(id=viyar) close;",
                 output = "html")
writeLines(r$html[[1]], "means.html")

r$html is named for the files the server generated (sashtml.htm, sashtml1.htm, ...), not for the procedures that produced them.

Folders and files

Two separate storage systems, two separate function families:

  • SAS Content (the Files/Folders app in Viya): viya_create_folder(), viya_upload(), viya_download(), viya_delete_file(), viya_delete_folder().
  • The compute session's own filesystem (a home directory, an NFS-mounted shared path, or anything else the session process can see on disk): viya_fs_mkdir(), viya_fs_upload(), viya_fs_download(), viya_fs_list(), viya_fs_delete(). These need an active compute session (h) and operate on that session's real filesystem, not the Files/Folders app. Note that a path can be readable without being writable (e.g. an NFS-mounted home directory with restrictive permissions) — /tmp is a reliable writable scratch location if you hit unexpected 404s on viya_fs_mkdir()/viya_fs_upload().
viya_create_folder(h, "/Public/Reports/2026")
viya_upload(h, "report.html", "/Public/Reports/2026")
viya_delete_file(h, "/Public/Reports/2026/report.html")
viya_delete_folder(h, "/Public/Reports/2026")

viya_fs_mkdir(h, "/nfs/homes/user/reports/2026")
viya_fs_upload(h, "report.html", "/nfs/homes/user/reports/2026/report.html")
viya_fs_list(h, "/nfs/homes/user/reports/2026")
viya_fs_delete(h, "/nfs/homes/user/reports/2026")

SAS Clinical Acceleration Repository

A third, separate storage system, available only on clusters licensed for SAS Clinical Acceleration. It is a governed hierarchy — contexts (organizations, studies, deliveries, ...) hold folders, which hold files — and viyar reads it without a compute session, so these functions take token/url rather than a handle h:

viya_clinical_item()                    # the repository root
viya_clinical_list()                    # top-level contexts
viya_clinical_list("/Acme/Study 1")     # everything inside a study
viya_clinical_types()                   # what the type_id column means

viya_clinical_find("contains(name,'Acme')")   # search the whole tree by name
viya_clinical_find("eq(name,'protocol.sas')")

viya_clinical_download("/Acme/Study 1/protocol.sas", "protocol.sas")
viya_clinical_download("/Acme/Study 1", "study1.zip")  # a container
utils::unzip("study1.zip", exdir = "study1")

viya_clinical_list() returns name, id, type (CONTEXT, FOLDER or FILE), type_id, path, size, state and modified, and it pages through the whole container rather than stopping at the first page. viya_clinical_find() returns the same shape, but searches across the whole repository by an RQL filter expression (eq, ne, contains, startsWith, ... combinable with and/or/not) instead of listing one known container's children — useful when you don't know, or can't get right, the exact path to something.

A file downloads as itself. A context or folder downloads as a ZIP archive of everything under it. The service sends no file name either way, so give local_path the full destination name. Writing is covered below.

Changing repository content

Add new files with viya_clinical_upload(). To change an existing file, check it out, edit your local copy, and check it back in:

viya_clinical_create("/Acme/Study 1/programs")          # a folder
viya_clinical_upload("adsl.sas", "/Acme/Study 1/programs")

f <- "/Acme/Study 1/programs/adsl.sas"
viya_clinical_checkout(f, "adsl.sas", overwrite = TRUE)
# ...edit adsl.sas...
viya_clinical_checkin(f, "adsl.sas", comment = "Derive TRTSDT from EX")
# or, to give up instead of checking in: viya_clinical_undo_checkout(f)

viya_clinical_update(f, name = "adsl_v1.sas")           # rename
viya_clinical_delete("/Acme/Study 1/programs/adsl_v1.sas")  # to the recycle bin

What you can do depends on your repository permissions. Creating a top-level organization needs Clinical Administrators membership, and deleting a context needs permanent = TRUE plus the "Permanently Delete Items" privilege. A deployment can also refuse some file extensions; the error message names the extension.

If you already have a compute session, reuse its credentials rather than configuring them twice:

h <- viya_session()
viya_clinical_list("/", token = h$token, url = h$base)

Authenticating to SAS Viya

Workbench is the easiest place to use viyar. An administrator registers the OAuth client once, in the Workbench integration. After that, no user has to ask for a client, open a browser, paste a code back or set a token. Everywhere else, each user needs a registered client of their own (see OAuth client for viya_login()). In Workbench:

  • viya_session() works with no setup. viyar finds both the token and the Viya URL from the integration.

  • It works in scripts, not just the console. Background jobs, notebook kernels and quarto render inherit the Workbench session, so a rendered document can run SAS with no interactive login.

  • Credentials come from Workbench each time they are needed, so there is no token to copy, store or refresh by hand.

  • Workbench: managed OAuth credentials via rstudioapi (integration name configurable, default ^sas-viya$). The Viya URL is auto-detected from the integration if viya_config(url = ...)/VIYA_URL isn't set.

  • Local desktop R (outside Workbench): viya_login() opens a browser SSO login (authorization code + PKCE) and caches the resulting token, refreshing it automatically as it nears expiry. SAS Logon only accepts OAuth clients an administrator has registered, and the default client_id = "vscode-positron" and out-of-band redirect_uri are rejected on some servers (the browser shows "The request is invalid"). Ask your administrator for a registered public client and override them: viya_login(client_id = "my-client", redirect_uri = NULL). It needs an interactive session; use VIYA_TOKEN in scripts.

  • Posit Connect: obtain a viewer token with connectapi and pass it: viya_session(token = viewer_token).

  • Anywhere: set VIYA_TOKEN.

Requirements

  • R 4.1.0 or later. No Python, reticulate or swat needed.
  • R packages installed with viyar: httr2 (1.0.0 or later), curl, jsonlite and openssl.
  • A SAS Viya 4 deployment that you can reach over HTTPS, and an account on it. viyar uses REST only: the Compute, CAS Management and Files/Folders services.
  • A way to get a token, one of:
    • Posit Workbench with a SAS Viya managed OAuth integration (needs rstudioapi).
    • viya_login() for browser SSO outside Workbench. This needs an OAuth client that a Viya administrator has registered on SAS Logon; see OAuth client for viya_login().
    • A token you already have, in the VIYA_TOKEN environment variable. Posit Connect uses this route with a viewer token (needs connectapi).
  • Optional:
    • knitr, to use the {sas} chunk engine in Quarto documents.
    • SAS Clinical Acceleration on the cluster, for the viya_clinical_*() functions. It is separately licensed. Creating a top-level organization needs Clinical Administrators membership.
    • testthat, pkgload and withr, to run the tests. The live tests also need a cluster and a token; see CLAUDE.md.

OAuth client for viya_login()

SAS Logon rejects authorization requests from clients it does not know, with the unhelpful message "The request is invalid". The default client_id = "vscode-positron" exists only where an administrator registered it, so on most servers you must ask your Viya administrator for a client with these settings:

Setting Value
Client type Public: no client secret (viyar sends none; it uses PKCE)
Grant types authorization_code and refresh_token
Scope openid
Redirect URI urn:ietf:wg:oauth:2.0:oob (the default), or any URI you pass as redirect_uri

Then pass the client id to viya_login():

viya_login(url = "https://viya.example.com", client_id = "my-client")
# If the client has a single registered redirect URI, let the server use it:
viya_login(url = "https://viya.example.com", client_id = "my-client",
           redirect_uri = NULL)

Without refresh_token, you have to log in again whenever the token expires. Skip all of this if you use Workbench managed OAuth or set VIYA_TOKEN.

Installation

viyar is not on CRAN. Install it from GitHub:

# install.packages("pak")
pak::pak("sol-eng/viyar")

Or with remotes:

# install.packages("remotes")
remotes::install_github("sol-eng/viyar")

License

MIT. See LICENSE.

About

R package for working with SAS Viya

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages