philihpAboutPGPLightning

For loops in SAS

Philihp Busby,2 min read

When coding for loops in SAS, one neat thing to remember is that all of the parts of it are optional.

DO variable=start
  <TO stop>
  <BY increment>
  <WHILE(expression) | UNTIL(expression)>
  ...
END;

http://support.sas.com/documentation/cdl/en/lrdict/62618/HTML/default/a000201276.htm

So in another language, what might be

for(int i=0;i < max;i++) {

In SAS, you can leave out the “by 1”, since it’s the default increment. So this would be

do i=0 to max;

What’s fun is in SAS you can combine a Repeat-Until/Do-While  loop with a for loop. This might be useful if for some reason you don’t set the var “max” until you’ve iterated through the loop once, such as in this case, where “metadata_getnobj ” returns a negative on fail, but otherwise returns the number of objects that match the query.

do i=1 by 1 until (i >= objs); rc=metadata_getnobj("omsobj:SASLibrary?@Libref='MYLIBREF'",i,uri); if rc>=0 then objs=rc; rc=metadata_getnasn(uri,"LibraryConnection",1,uri); if rc>=0 then leave; end;

This code loops through all the libraries in the metadata with libref=‘MYLIBREF’, and exits with a URI for the first one it sees with at least one LibraryConnection association. This is useful when you have a remote library pointing to a local library and they both have the same name and you want a URI to the remote one.

Another cool thing with FOR loops in SAS is iteration through lists. In Java, say you have a block like this:

for(String x : new String[] { "a","b","c" }) { System.out.println("x="+x); }

In SAS, this is simply

do x="a","b","c"; put x=; end;

GitHub · Bluesky · LinkedIn · Instagram · KeybaseRSS

Built from 8f0906ac CC BY 4.0 — with love from San Francisco.