Writing
Run a SAS Script from R
Unlike SAS, which can host an R session after the right setup, R cannot host a SAS session directly.
R can, however, call operating-system commands with system(). SAS can also run a .sas script from the command line. Connecting these two sides together, an R script can launch SAS and run a .sas script file.
The command-line syntax for running a SAS script is:
"C:\Program Files\SASHome\SASFoundation\9.4\sas.exe" -SYSIN "path\to\example.sas"
In R, call that command through system():
system('"C:\\Program Files\\SASHome\\SASFoundation\\9.4\\sas.exe" -SYSIN "path\\to\\example.sas"')
There are two small details to notice:
- The full command is wrapped in single quotes because the command itself uses double quotes to protect paths that may contain spaces.
- Backslashes
\are escaped with additional backslashes in the R string.
That one-line command works, but it is hard to modify. Splitting the command into pieces makes the code easier to read and extend:
sas_exe = '"C:\\Program Files\\SASHome\\SASFoundation\\9.4\\sas.exe"'
sas_script = '"path\\to\\example.sas"'
sas_command = paste0(sas_exe, " -SYSIN ", sas_script)
system(sas_command)
You can expand this approach to make it easy to add configuration, autoexec, log, and output paths:
sas_exe = '"C:\\Program Files\\SASHome\\SASFoundation\\9.4\\sas.exe"'
sas_cfg = '"C:\\Program Files\\SASHome\\SASFoundation\\9.4\\sasv9.cfg"'
sas_autoexec = '"my\\autoexec.sas"'
sas_script = '"path\\to\\example.sas"'
sas_log = '"path\\to\\sas.log"'
sas_lst = '"path\\to\\sas.txt"'
sas_command = paste0(sas_exe,
" -CONFIG ", sas_cfg,
" -AUTOEXEC ", sas_autoexec,
" -NOSPLASH",
" -SYSIN ", sas_script,
" -LOG ", sas_log,
" -PRINT ", sas_lst)
system(sas_command, intern = TRUE, invisible = FALSE)
Your SAS installation path may be different, so adjust the paths if the example does not run on your machine.