Unlike SAS, which provides designated syntax to run a R session alongside the SAS session, R does not have the capability to run a SAS session.
However, R has the function system()
to invoke any command from the OS. On the other hand, SAS provides a functionality to allow us to run a SAS script through command line. By putting those two together, we can use R to call the SAS command to run a SAS script.
The command line syntax to call SAS to run a SAS script is:
1 |
"C:\Program Files\SASHome\SASFoundation\9.4\sas.exe" -SYSIN "path\to\example.sas" |
All we need to do is call the above command from the R system()
function. The R code will look like:
1 |
system('"C:\\Program Files\\SASHome\\SASFoundation\\9.4\\sas.exe" -SYSIN "path\\to\\example.sas"') |
Notice two small changes:
- The whole command is put within the single quotes because we use double quotes in the command, which is because the paths could have spaces in it.
- Backslashes
\
are escaped with additional backslashes for the R syntax.
The above code is hard to modify and expand. We can make things easier by splitting the pieces and paste them back together.
1 2 3 4 |
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) |
Using the above syntax, we can add more to the SAS command:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
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) |
Note: the SAS installation path can be different, please check if the above code does not run on your machine.
One thought on “Run SAS Script in R”