Tuesday, April 30, 2013

SAS - See if macro variable exists; delete macro variable

This program shows how to see if a macro variable exists, as well as how to delete a macro variable.

%let chk = %symexist(myvar);
%put chk = &chk;        /* output: chk = 0   */
%let myvar = xyz;
%let chk = %symexist(myvar);
%put chk = &chk;        /* output: chk = 1   */
%symdel myvar;          /* delete macro var  */
%let chk = %symexist(myvar);
%put chk = &chk;        /* output: chk = 0   */
%symdel myvar;          /* gives a warning   */
%let chk = %symexist(myvar);
%put chk = &chk;        /* output: chk = 0   */
%symdel myvar /nowarn;  /* gives no warning  */
%let chk = %symexist(myvar);
%put chk = &chk;        /* output: chk = 0   */



Here is the log:

NOTE: Copyright (c) 2002-2010 by SAS Institute Inc., Cary, NC, USA.
NOTE: SAS (r) Proprietary Software 9.3 (TS1M1)
      Licensed to FIRST ANALYTICS, Site 70073576.
NOTE: This session is executing on the W32_7PRO  platform.



NOTE: Updated analytical products:

SAS/STAT 9.3_M1, SAS/ETS 9.3_M1, SAS/OR 9.3_M1

NOTE: SAS initialization used:
      real time           3.98 seconds
      cpu time            3.05 seconds

1    %let chk = %symexist(myvar);
2    %put chk = &chk;        /* output: chk = 0   */
chk = 0
3    %let myvar = xyz;
4    %let chk = %symexist(myvar);
5    %put chk = &chk;        /* output: chk = 1   */
chk = 1
6    %symdel myvar;          /* delete macro var  */
7    %let chk = %symexist(myvar);
8    %put chk = &chk;        /* output: chk = 0   */
chk = 0
9    %symdel myvar;          /* gives a warning   */
WARNING: Attempt to delete macro variable MYVAR failed. Variable not found.
10   %let chk = %symexist(myvar);
11   %put chk = &chk;        /* output: chk = 0   */
chk = 0
12   %symdel myvar /nowarn;  /* gives no warning  */
13   %let chk = %symexist(myvar);
14   %put chk = &chk;        /* output: chk = 0   */
chk = 0


Here are the SAS doc links:
For symexist:  http://support.sas.com/documentation/cdl/en/mcrolref/61885/HTML/default/viewer.htm#a002635883.htm
For symdel:  http://support.sas.com/documentation/cdl/en/mcrolref/61885/HTML/default/viewer.htm#a001651249.htm



Thursday, April 18, 2013

SAS - Temporary variables

Lifted this from http://www.afhood.com/blog/?tag=temporary-variables

This is a great practice that we picked up from the guys over on SAS-L. It is a way to create temporary variables in datasteps that are dropped before being written to the output dataset.
data output_dataset (drop=_:);
set input_dataset;
_temp_var = ;
new_variable = ;
run;
The variables beginning with the underscore ("_") will be dropped before being written to the output dataset. It doesn't matter if there is one temp variable or 1000. As long as they begin with an underscore, they will not make it to the output dataset.  If you use this drop statement without creating any temporary variables you will get a warning.

Just the information I was looking for this morning! Thanks.