Tuesday, December 3, 2013

SAS: Temporary arrays

Spent way too much time last night trying to determine why a program was taking too long to run.  The time to run increased exponentially -- rather than linearly -- as more records were processed.  I determined that it was too much reliance on symget and symput.  When I used a temporary array instead, the program ran very quickly.

The following statement will create an array of numeric variables. Key points with temporary arrays:
  • You must specify the size with a numeric constant (or, as I did here, with a macro variable which evaluates to a numeric constant.)
  • Temporary arrays are automatically retained.
  • Temporary arrays are not written to the output data set.

Note how I was able to initialize all entries to zero.

      array used [&_NVARS] _temporary_ (&_NVARS * 0);


Here I check the value of an element in the array:

      if (used[&i] = 0) then do;

Here I set the value of an element in the array:

      used[save_i] = 1;







Friday, November 15, 2013

SAS: Double dash

Use double-dash to indicate a range of variables (in the order they are defined in the program data vector, I assume).

Source code:

    data _null_;
    input a b c $ d e $ f;
    put b--e;
    datalines;
    1 2 w 4 x  6
    2 4 y 8 z 12
    ;
    run;



Log:

    2 w 4 x
    4 y 8 z



Friday, November 1, 2013

SAS: Concatenate strings and numbers using CATX function

No more trim'ing and left'ing!  SAS' CATX function lets you concatenate strings and numbers!

Source code:

    data _null_;
    attrib result length=$20;
    input name $ date_as_number : anydtdte12. ;
    date_as_string = put(date_as_number, mmddyy10.);
    result = catx("*", name, date_as_number);
    put result=;
    result = catx("*", name, date_as_string);
    put result=;
    datalines;
    Cora 19840723
    Hannah 19880626
    Emma 19900411
    ;
    run;


Log:


    1    data _null_;
    2    attrib result length=$20;
    3    input name $ date_as_number : anydtdte12. ;
    4    date_as_string = put(date_as_number, mmddyy10.);
    5    result = catx("*", name, date_as_number);
    6    put result=;
    7    result = catx("*", name, date_as_string);
    8    put result=;
    9    datalines;

    result=Cora*8970
    result=Cora*07/23/1984
    result=Hannah*10404
    result=Hannah*06/26/1988
    result=Emma*11058
    result=Emma*04/11/1990
    NOTE: DATA statement used (Total process time):
          real time           0.09 seconds
          cpu time            0.04 seconds


    13   ;
    14   run;



Friday, July 19, 2013

SAS: Permissive Delete

I recently had a lot of problems with evening processes failing due to lack of disk space:


ERROR: Insufficient space in file PERM.SRA_ANALYTICS_DSS_T.DATA.
ERROR: File PERM.SRA_ANALYTICS_DSS_T.DATA is damaged. I/O processing did not complete.


My project leader pointed out the following:


From the web… SAS does not overwrite datasets at once, but creates a copy and after successful end of a step, the old dataset is deleted and the intermediate file is renamed.

He suggested we delete the file before attempting to write the new one.  So I wrote a macro to conditionally delete the file.  Back in the old days, some of use mainframers called this a "permissive delete", hence the name of the macro.

Here's the macro:

%macro PERMISSIVE_DELETE(SASFILE=);
%if %sysfunc(exist(&SASFILE)) %then %do;
    proc sql noprint;
    drop table &SASFILE;
    quit;
    run;
    %put *** File &SASFILE deleted.;
%end;
%else %do;
    %put *** File &SASFILE already deleted.;
%end;
%mend PERMISSIVE_DELETE;


Here's the test program:

libname Perm "C:\TEMP";
%let TBL_MY_FILE = Perm.Junk;

data &TBL_MY_FILE;
name = "Bill";
age = 56;
run;

proc print data=&TBL_MY_FILE;
run;

* Should delete ;
%PERMISSIVE_DELETE(SASFILE=&TBL_MY_FILE);

* Should be gone already ;
%PERMISSIVE_DELETE(SASFILE=&TBL_MY_FILE);


Here's the significant portion of the log:

24
25   * Should delete ;
26   %PERMISSIVE_DELETE(SASFILE=&TBL_MY_FILE);
NOTE: Table PERM.JUNK has been dropped.
NOTE: PROCEDURE SQL used (Total process time):
      real time           0.02 seconds
      cpu time            0.00 seconds


*** File Perm.Junk deleted.
27
28   * Should be gone already ;
29   %PERMISSIVE_DELETE(SASFILE=&TBL_MY_FILE);
*** File Perm.Junk already deleted.



Thursday, June 27, 2013

Unix: System date and time to a variable, and using that variable



Caveat: I am a Unix novice.  There may be better ways to do this, but this worked for me.

Show system date and time in the default format:
$ date
Thu Jun 27 21:23:36 CDT 2013

Show system date and time in yymmdd_hhmmss format (two digit year):
$ date "+%y%m%d_%H%M%S"
130627_212355

Show system date and time in yyyymmdd_hhmmss format (four digit year):
$ date "+%Y%m%d_%H%M%S"
20130627_212416

Save the system date and time in yyyymmdd_hhmmss format to a variable, then show it:
$ var="$(date '+%Y%m%d_%H%M%S')"
$ echo datetime is $var
datetime is 20130627_212437

My requirements: Schedule a SAS program (pd.sas) to run at 4am on June 28th.  Send the SAS log to a file whose name includes the system date and time so we can archive the logs.

Step 1: Create a (script) file called go
#!/bin/bash
ts="$(date '+%Y%m%d_%H%M%S')"
echo "sas pd.sas -log pd_$ts.log" | at 0400 Jun 28
Step 2: Execute a (script) file called go
$ . go

Monday, June 24, 2013

Python: Reading a JSON dataset

I just completed an online Python course.  I have been experimenting and there is much about this language to love!

Here is a simple JSON dataset, called min_max_json.txt:

{
"min": 34,
"max": 82
}


Here is the source code, called read_min_max_json.py, which reads the JSON dataset and calculates the range (defined as max - min):

import json
data = json.loads(open('min_max_json.txt').read())
print("This is what was read in:")
print(data)
min = data["min"]
max = data["max"]
range = max - min
print("The range is " + str(range) + ".")


Here is the output:

This is what was read in:
{'min': 34, 'max': 82}
The range is 48.


Note: Using Python 3.3.2 with IDLE.


Thursday, May 30, 2013

SAS: Get file creation date

I needed to know when a SAS file had been created, because I did not want a nightly process to replace the file if it had been manually created that same day.  This code will get the creation date of a file (any file, not just a SAS file) and save it as a SAS date in a macro variable.

I got burned with this, not knowing that Windows and Linus would return the date in completely different formats!

     Windows returned:  Wed May 29 22:02:21 2013
     Linus returned:  29May2013:22:02:21

Hence the use of the substr function below.

* What is the creation date of the existing file? ;
* See http://support.sas.com/kb/38/267.html ;
data _null_;
rc = filename("myfile", "full_path_and_filename_here.ext");
put rc=;
fid = fopen("myfile");
infonum = foptnum(fid);
do i = 1 to infonum;
    infoname = foptname(fid, i);
    infoval = finfo(fid, infoname);
    put infoname= infoval=;
    if (infoname = "Last Modified") then do;
        if ("&SYSSCPL" = "Linux") then do;        * Wed May 29 22:02:21 2013 ;
            year = substr(infoval, 21, 4);        * 2013 ;
            month = substr(infoval, 5, 3);        * May ;
            day = substr(infoval, 9, 2);          * 29 ;
            time = substr(infoval, 12, 8);        * 22:02:21 ;
            together = trim(day) || trim(month) || trim(year) || ":" || trim(time);  

            * Now it is 29May2013:22:02:21, same as Windows now ;
            put together=;
            createDateTime = input(together, anydtdtm20.);
            createDate = datepart(createDateTime);
        end;
        else do;
            createDateTime = input(infoval, anydtdtm20.);
            createDate = datepart(createDateTime);
        end;
        put createDate=;
        call symput("CREATE_DATE", trim(left(createDate)));
    end;
end;
close = fclose(fid);
run;

%put *** CREATE_DATE=&CREATE_DATE;