Linking Code Chunks Using ‘sas_collectcode’

Doug Hemken

Jul 2017

Linking SAS code chunks makes use of SAS's autoexec.sas file. Within R this requires setting up a chunk option by invoking the sas_collectcode function.

Configure SAS and call "sas_collectcode".

require(SASmarkdown)
if (file.exists("C:/Program Files/SASHome/SASFoundation/9.4/sas.exe")) {
  saspath <- "C:/Program Files/SASHome/SASFoundation/9.4/sas.exe"
} else {
  saspath <- "sas"
}
sasopts <- "-nosplash -ls 75"

sas_collectcode()

Then set up SAS code chunks.

To have the effects of one code chunk available to use in a later code chunk, set the chunk option "collectcode=TRUE".

In this example, a data set is copied to the WORK library and only one variable is kept.

In Rmarkdown this would look like:

```{r datastep, engine="sas", collectcode=TRUE, engine.path=saspath, engine.opts=sasopts, comment=""}
data class;
    set sashelp.class;
    keep age;
    run;
```

And in your final document it would appear as:

data class;
    set sashelp.class;
    keep age;
    run;

A later step - using the WORK data.

Without collectcode to link the code chunks, a later chunk that referenced the data in the WORK library would produce an error, but this now works. (No special option is needed for this later step.)

proc means data=class;
run;
                            The MEANS Procedure

                         Analysis Variable : Age 
 
     N            Mean         Std Dev         Minimum         Maximum
    ------------------------------------------------------------------
    19      13.3157895       1.4926722      11.0000000      16.0000000
    ------------------------------------------------------------------