SAS Code Samples

by Richard A. DeVeneziaSend Feedback

These code samples have been culled from various work experiences, programming experiments and snippets posted to newsgroup comp.soft-sys.sas (SAS-L)

These sources are presented as-is. Use at your own risk.

New samples
report hbar, sudoku, spinward gradient, spinward animgif, jumble, dairy-herd, 200 plots, apache log, amicable numbers, hash-8, joy, hash-7, jDSGI,

Unix utility
Sample Explanation
dir.c C program to output filesize, file modification date (m/d/Y T), and filename. Useful for processing groups of input files.
hex.c Hex dump a file for detailed examination.
hexcat.c Similar to hex, but honors newlines found in file.
mac2ux.c Pipe fitting to convert files with \r line termination to \n line termination.
mdate.c Return modification date of a file.

Windows utility
Sample Explanation
windows-ipaddress Windows - Determine TCP/IP internet address
Posted to SAS-L Nov 03, 1999.
Adapted from Randy Birch code at VBnet
windows-no-x-icon Windows - Disable Close menu item (and X icon) in the system menu of a SAS session
Look Ma, no X
splash-countdown Generate jpg images and display them in a borderless window as a series of splash images. Requires windows program Splash.exe.
uga.vbs.txt Small visual basic program to open the www.listserv.uga.edu web interface to SAS-L, showing newest posts first. This code could easily be adapted to a bookmarklet.

General utility
Sample Explanation
constant Demonstrates lack of optimization by DATA Step compiler. Advice: Don't use constant() inside a large loop.
date-formats Lists the output of every SAS date related format. The log.
table-extract read-html-data perl script to extract data embedded in an html tablesas program to run perl script so it can read data extracted from web page
uuencode uuencode implemented in a SAS DATA Step
read-web-log Use SAS to read an Apache web server log file in common format

Data processing
Sample Explanation
beers-n-bars Which bars sells the beers a drinker likes ? Or Which sets contain which subsets. SQL and bitcoding.
bit-count Count the number of bits set to 1 in an integer value
bit-reverse Reverse the order of the bits of an integer value
cartesian-join From a set of N points, keep only the pairs of points which are closer than some threshold. A Data step solution and an exquisite SQL solution by Howard Schreier.
dairy-herd Determine which calves were exposed to shedding dams
hash-1 DATA Step hashes performing a frequency analysis
hash-2 Rediscover the paths traversed by wandering subjects and report on them
hash-3 Some pitfalls you might encounter. Read access violation and missings turned into zeros.
hash-4 Transpose and concatenate satellite data while key merging disordered sets.
hash-5 Sum amounts in a transactional trail.
hash-6 Split a table into subset tables based on variable values aka Split one data set into several data sets named according to a group variable.
Material posted in 24MAY2004 SAS-L thread "Hash of hashes and dynamic output"
hash-7 Hash of hashes idea (see hash-6) expanded into a useable multi-level-hash (MLH) construct by using macros. See multi-level-hash for the macros. An MLH in essence provides for arbitray navigation of the class levels of a hierarchy within the providence of a DATA Step.
Important: Any PROC Step that provides a CLASS or BY statement allows you to process data that is hierarchically segregated into groups. Use Procs instead of MLH in most every case.
Additionally, in many DATA Step situations that involve hierarchical data and hashes, consider composite keys (one hash with >1 key variable) instead of MLH. (There are probably some theorems in computer science regarding the equivalences of one multi-keyed hash to N hashes that partition the key set.)

I have yet to find a reasonable sample problem that demonstrates MLH as the principally simplest solution technique. If one is found it will probably involve atypical path following algorithms or recursive searches. MLH is a technique waiting for a problem.

hash-8 In a set of dual keyed things find the groups of things chain related by key1 or key2, aka
A response to 17AUG2004 SAS-L thread "How to group people by their first name OR last name"
how-much-hotter-it-got A pot can contain 20 components. The temperature is known for every combination of components. How much hotter does the pot get when one new component is added to the pot?
increment-every-other Increment a counter every other observation.
index-within-group Seven techniques for calculating a within by group sequence number (What row in this group is this observation ?)
_infile_ buffer Input data directly from a character expression by managing the _infile_ buffer. (Sort of like C's sscanf)
jumble Solve the popular newspaper word puzzle
least-likes A collection of like clauses likely overlaps. What are the fewest like clauses that would match the same things as all the like clauses.
mapped-lookup A DATA Step processing an atypical data structure requiring the assignment
a_new = value of variable ("a_" || n) uses a functional mapping to avoid more complicated general purpose hash.
polygon-hunt An unordered data set of line segments having unique vertices are known to be pieces of polygons. Enumerate the vertices of each polygon and indicate if the order is clockwise or counter-clockwise.
random-schema Create a SAS library containing a complicated schema involving dozens of tables and dozens of referential relationships.
rolling-back-sums At time T, a computation based on attribute values in prior observations occurring within prior interval I is to be made. Sample involves buying and selling volumes. Adaptable to any process requiring a rolling back calculation.
Net volumes of prior period
rxparse-in-macro How to use rxparse, rxchange and rxfree in macro
split-into-words Split a long character value into several shorter character variables (splits) while ensuring the splits contain only whole words
superset Find the fewest mutually exclusive supersets S* such that each S* contains all sets S sharing at least one member. Demonstrates how to program a recursive algorithm using GOTO and ARRAY to emulate functional calls with stacks.
Animation of program flow

ODS - Output Delivery System
Sample Explanation
pdf-bullets Characters in ITC Zapf Dingbats font make excellent pdf bullets. Generate a sample showing each.
pdf-bullets Place bulleted text in a pdf document.
excel-multisheet Use windows shell script to create a new Excel workbook containing several worksheets, each populated from an html file. Each html file is generated using ODS and contains Proc TABULATE results for one by-group.
report hbar Generate hbar charts per by group using Proc REPORT and ODS. Sample output.
tabulate Proc TABULATE - Use the page dimension of tabulate to place a title above each table created in a single Proc step. Sample output.
tabulate-with-graph Generate a two page report in pdf format (100k,uncompressed). Contains a tabulation and vertical bar charts.

Visualization
Sample Explanation
annontated-chart A stacked vbar chart annotated to display counts of another subgroup
axis-with-partial-minor-ticks Plot with an axis having only some minor tick marks
bezier-curves Bezier curves inside a circle. (DSGI)
cowboy-hats Use GREPLAY to print 200 plots, 2 plots per page.
Sample uses 200 cowboy hat plots.
font-dump View all characters of any or all SAS fonts. Windows platform can also examine true type fonts. Notes: SAS font samples can also be found in the OnlineDoc. Special symbols that can be indicated in a SYMBOL statement can also be found in the SPECIAL font.
font-zodiac Zodiac and planetary symbols are found in the SAS SPECIAL font.
Zodiac symbols found in SAS SPECIAL font
G3D-annotated Surface function plot annotated with data points. Change in view point animated using gifanim graphics device. Sample output.
gchart A stacked vertical bar chart with groups.
gfont-quadrants SAS/Graph custom font created with Proc GFONT. The sixteen possibilities of a circle with it's quadrants filled and unfilled. This font uses circular arcs, which in my estimation contains too few sampling points. A thumbs down on circular arcs.
Sixteen circles with filled and unfilled quadrants
gfont-moon-phase SAS/Graph custom font created with Proc GFONT. Shows N phases of the moon. You choose N. This font does it's own arc computations and at small sizes looks better than if SAS circular arcs were used.
Moon phases
jDSGI
 Gallery
 Macros
Java DATA Step Graphics Interface - A combination of Java classes and SAS macros that let you can create almost any type of static 2D visualization as an image file (PNG and JPG are built into JRE). The impetus for this development was the lack of antialiased line drawing in SAS/Graph.

Additional graphic formats are supported by adding ImageIO jars to your JRE lib/ext folder. See Java Advanced Imaging and download I/O Tools.
Note: Windows users must set an undocumented environment variable for their SAS sessions. Use command line option -set TKJNISETLOADER y

Java sources: Graphics, ViewportTransform, and DoubleArray
jDSGI.zip - The gallery codes zipped together and ready to roll.
l1-traveling-salesman A traveling salesman, cities on a grid and shortest path to next city. Cities can be made to exist on a spiral :).
Travels of a salesmanTravels of a salesman
month-o-charts A month's worth of bar charts in a html page
polar-time-plot
DSGI polar plot  vs.  GPLOT XY plot
Polar presentation of data XY presentation of data
schema-ball Graph the foreign key relationships of tables in a library. (DSGI)
Inspired by Martin Krzywinski's schemaball.
Run the random-schema program to fill a library with randomly related tables.
state-chain An NPR puzzle: The last two letters of ALASKA are the first two letters of KANSAS. Can you find a chain of five state names that overlap like this, in which the last two letters of each are the first two letters of the next. See the answer.
vbar-by-group Ensure all midpoints are same patterned even when some by groups do not contain all midpoints found across all the by groups. Sample output.

Diversions
Sample Explanation
amicable-numbers A pair of numbers, the factors of each when summed is the other.
descent Artistic descent An n-sided regular polygon rotating a fixed amount and shrinking to be circumscribed by the previous iteration. Iterations are colored according to a linearly interpolated rgb gradient. (DSGI)
joy-to-the-world Generate wave forms of pure tone notes and play them back through the audio device in the form of the song "Joy to the World". Tested on Windows 2000.
spinward-animation
spinward-gradient
An animation of triangles that spiral inward once they fill your viewport. A inward spiraling gradient within nested triangles
Animated triangles Gradient triangles
sudoku Solve Sudoku puzzles using a path walker. Simple front end for tracing through each step.
trick-problem Consider
data fakedata;
  x = 0;
  do while (x<100);
    y = ranuni(0);
    output;
    * increment by one or two;
    x + 1 + ranuni(0)<0.25;
  end;
run;
A. What is the most number of rows table fakedata could have ?
B. What is the least number of rows table fakedata could have ?

These sources are presented as-is. Use at your own risk.

This page was last updated 30 May 2007.