Sas Macros Cheat Sheet



  1. R to SAS cheatsheet - a collection of snippets. This list was created to quickly translate a R code to its equivalent in SAS. I wrote these snippets to be as short as possible and to reflect my own coding style. There are many ways to skin a cat: you might know another way to write a similar code in R and SAS.
  2. When the MDR moves to Capacity Services, SAS Enterprise Guide (EG) will be available to all users. This software package is considered more user -friendly than U NIX and Base SAS and includes a query builder with more point and click capability. However, basic knowledge of SAS code is still necessary even when using EG.

Have you ever tried to pass comma-delimited values to SAS macro or to a SAS macro function? How can SAS distinguish commas separating parameters or arguments from commas separating parts of the values?

The SAS® Macro Language is a powerful tool for extending the capabilities of the SAS System. This hands-on workshop teaches This hands-on workshop teaches essential macro coding concepts, techniques, tips and tricks to help beginning users learn the basics of how the Macro language.

Passing comma-delimited value as an argument to a SAS macro function

Let’s say you want to extract the first word from the following string of characters (these words represent column names in the SASHELP.CARS data table):

make, model, type, origin

If you run the following code:

%let firstvar = %scan(make, model, type, origin, 1);

you get is the following ERROR in your SAS log:

ERROR: Macro function %SCAN has too many arguments.

That is because %scan macro function sees and treats those make, model, type and origin as arguments since commas between them are interpreted as argument separators.

Sas macros cheat sheet excel

Even if you “hide” your comma-delimited value within a macro variable, it still won’t do any good since the macro variable gets resolved during macro compilation before being passed on to a macro or macro function for execution.

%let mylist = make, model, type, origin;
%let firstvar = %scan(&mylist, 1);

You will still get the same ERROR:

ERROR: Macro function %SCAN has too many arguments.

Passing comma-delimited value as a parameter to a SAS macro

Try submitting the following code that passes your macro variable value to a SAS macro as a parameter:

You will get another version of the SAS log ERROR:

Clean up memory on computer windows 10

ERROR: All positional parameters must precede keyword parameters.
NOTE: Line generated by the macro variable 'MYLIST'.
1 type, origin
----
180
ERROR 180-322: Statement is not valid or it is used out of proper order.

In this case, macro %subset gets as confused as the %scan function above because your macro variable will get resolved during macro compilation, and SAS macro processor will see the macro invocation as:

%subset(dsname=SASHELP.CARS, varlist=make, model, type, origin)

Macro sas put

treating each comma as a parameter separator.

All this confusion happens because SAS functions’ arguments and SAS macros’ parameters use commas as their separators, while resolved macro variables introduce their own values’ comma delimiters into the functions/macros constructs’ picture, thus wreaking havoc on your SAS program.

It’s time for a vacation

But don’t panic! To fight that chaos, you need to take a vacation. Not a stay-home, do-nothing vacation, but some serious vacation, with faraway destination and travel arrangements. While real vacation is preferable, an imaginary one would do it too. I mean to start fighting the mess with comma-separated values, pick your destination, book your hotel and flight, and start packing your stuff.

Do you have a “vacation items list”? In my family, we have an individual vacation list for every family member. How many items do you usually take with you? Ten, twenty, a hundred?

Regardless, you don’t show up at the airport checkpoint with a pile of your vacation items. That would’ve been too messy. I don’t think you would be even allowed boarding with an unpacked heap of your stuff. You come to an airport neatly rolling a single item that is called a suitcase. Well, I suppose that some of you may have two of them, but I can’t imagine more than that.

You only started your fantasy vacation, you haven’t even checked in to your flight, but you have already have a solution in your sight, a perfect combine-and-conquer solution for passing comma-delimited values. Even if you have not yet realized that it’s in your plain view.

Thinking inside the box

Forget about “thinking outside the box” metaphor. Vivaldi armida. You can’t solve all your problems with a single strategy. Sometimes, you need to turn your thinking on its head to solve, or even to see the problem.

As for your airport check-in, instead of thinking outside the box, you thought “inside the box” and brought your many items “boxed” as a single item – a suitcase. A container, in a broader sense.

That is exactly how we are going to approach our comma-delimited lists problem. We are going to check them in to a macro or a macro function as a single, boxed item. Just like this:
Or like this:

Not surprisingly, SAS macro language provides a variety of these wonder boxes for many special occasions collectively known as macro quoting functions. Personally, I would prefer calling them “macro masking functions,” as they have nothing to do with “quoting” per se and have everything to do with masking various characters during macro compilation or macro processing. But that is what “macro quoting” means – masking, boxing, - similar to “quoting” a character string to make it a single entity.

Forget about the “thinking outside the box” metaphor. You can’t solve all your problems with a single strategy. Sometimes, you need to turn your thinking on its head to solve, or even to see the problem.

Different macro quoting functions mask different special characters (+ - , / ; = etc.) and mnemonics (AND OR GT EQ etc.) so that the macro facility interprets them as text instead of as language symbols.

Here are all 7 SAS macro quoting functions, two of which work at macro compilation - %STR() and %NRSTR(), while other 5 work at macro execution - %QUOTE() and %NRQUOTE(), %BQUOTE() and %NRBQUOTE(), and %SUPERQ().

You may look up what symbols they mask and the timing they apply (macro compilation vs. macro execution) in this macro quoting functions summary. You may also want to look at the following cheat sheet: Deciding When to Use a Macro Quoting Function and Which Function to Use.

Sas cheat sheet pdf

As general rule of thumb, use macro quoting functions at compilation time when you mask text constants - (make, model, type, origin); use macro quoting functions at execution time when you mask macro or macro variable references containing & or % - (&mylist).

NOTE: There are many other SAS macro functions that besides their main role also perform macro quoting, e.g. %QSCAN(), %QSUBSTR() and others; they all start with %Q.

Masking commas within a comma-delimited value passed as an argument or a parameter

It turns out that to mask (or to “box”) comma-separated values in a macro function or a SAS macro, any macro quoting function will work. In this case I would suggest using the simplest (and shortest) %STR(). %STR() applies during macro compilation and serves as a perfect “box” for our comma-delimited values to hide (mask) commas to receiving macro function or a macro does not confuse them with its own commas separating arguments / parameters.

With it we can re-write our above examples as:

%let firstvar = %scan(%str(make, model, type, origin), 1);
%put &=firstvar;

SAS log will produce exactly what we expected:

FIRSTVAR=make

Similarly, we can call the above SAS macro as:

%subset(dsname=SASHELP.CARS, varlist=%str(make, model, type, origin) )

It will run without ERRORs and produce a print of the SASHELP.CARS data table with 4 columns specified by the varlist parameter value:

Masking commas within a macro variable value passed as an argument or parameter

Sas cheat sheet pdf

When you assign a comma-delimited list as a value to a macro variable, we want to mask commas within the resolved value during execution. Any of the execution time macro quoting functions will mask comma.

Again, in case of multiple possibilities I would use the shortest one - %QUOTE().

With it we can re-write our above examples as:

But just keep in mind that the remaining 4 execution time macro quoting functions - %NRQUOTE(), %BQUOTE(), %NRBQUOTE() and %SUPERQ() - will work too.

NOTE: The syntax of the %SUPERQ() function is quite different from the rest of the pack. The %SUPERQ() macro function takes as its argument either a macro variable name without an ampersand or a macro text expression that yields a macro variable name without an ampersand.

Get it going

I realize that macro quoting is not a trivial matter. That is why I attempted to explain its concept on a very simple yet powerful use case. Hope you will expand on this to empower your SAS coding skills.

Tags learn sasProblem SolvingProgramming Tipssas programming

This article is mostly intended as a quick reference for myself.I cover a very limited subset of uses of various SAS statements and procedures;those which I have been using more or less repeatedly.

Libname documentation

Proc importdocumentation.

Remark: if nothing works, an easy way out is to use the import wizard (File -> Import Data).The generated command can then be saved in a file and inspected or modified.

CSV Files

Dbf files

INSEE dataset for instance

MS Access databases

Sas dataset from directory

To import C:pathtodirTable1.sas7bdat.

For someone who has been programming, SAS macros can feel very unintuitive.They are very much the tell-tale sign that the SAS language has been designedfor statisticians, not for developpers nor computer scientists.The easiest way to think reason about them is to think about the macro systemof the C preprocessor: SAS macro are mostly working as a text replacement tool,with some quirks.

Simplest macro:

Without variables, it is as simple as it gets.

With a loop

Variables, including loop variables, can be accessed with the &var. syntax.The loop syntax is close to for-loops in the usual languages.Documentation.

With parameters

As previously, we use the &var. syntax to access the content of a variable.

Using externally defined macro variables

This is a bit more tricky. Assume you want to loop through the columns in a table.One way to do it is to define macro variables with convenient names, convenientmeaning indexable.

The data _null_ statement allow one to operate without creating a dataset which isthe default behaviour.The symput('varname', v) function assigns a value v to a variable called 'varname'.In the loop body, we then use the usual &var. syntax to access the loop variable value.However, we are not done: we need to further resolve Colname&i. to what we have definedin the data step.For this, we use the &&var1&var2. syntax, meaning 'first resolve var2 to its value, thenresolve the resulting expression.The process as I figure it out in my mind is the follwing:&&Colname&i. -> &&Colname1 -> &Colname1. -> 'ID'.

Sas Operators Cheat Sheet

The sgplot procedure is fairly easy to use and flexible enough for most purposes.The only catch which has turned up to be utterly annoying is how the order of categoricalvariables is handled. I could not get it right even when sorting the data.The axescommand documentation is very useful.

Series for plotting lines

A simple example for theseriescommand.

A more complex example with groups, formats, custom colors and a legend.

Band for range of values

This one is very handy for plotting min - max values.

Vbar for vertical barplots.

Most of the options forvbarare valid forhbar.

Macro Sas Put

Grouping data:

Density to visualize 1-D distributions

Sgplot'sdensityis very simple to use.

A useful alternative is proc univariate'shistogram statement.

Plotting maps is a bit more involved so I wrote a dedicated article:Plotting maps in SAS.

Proc formatcan be helpful in various cases beyond the obvious usage. Here are some samples.

Defining intervals for numerical values

Getting a summary about missing values

Sas Hash Cheat Sheet

Writing the results of a query in a macro variable.

Datalines statement for making dummy datasets