Saturday, October 24, 2015

SAS: Initialize random number seed

Initialize random number seed:

&let SEED = 1234;

data _null_;
call streaminit(&SEED);

Saturday, October 17, 2015

R: Which package has this function?

Use the sos package in order to determine which package has a function you need.
findFn("partial residual plots")

Thursday, October 8, 2015

SAS: Drop variable if it exists

* =============================================================== ;
*         M A C R O   D R O P _ V A R _ I F _ E X I S T S
* =============================================================== ;

%macro drop_var_if_exists(SASFILE=,VAR=);

%* See also;

data _null_;
dsid = open("&SASFILE");
call symput("var_exists", varnum(dsid, "&VAR"));
rc = close(dsid);

%if (&var_exists eq 0) %then %do;
    %put Variable &VAR does not exist in &SASFILE ;
%else %do;
    proc sql noprint;
    alter table &SASFILE drop &VAR;
    %put Variable &VAR was dropped from file &SASFILE ;

%mend drop_var_if_exists;

* =============================================================== ;
*    T E S T   M A C R O   D R O P _ V A R _ I F _ E X I S T S
* =============================================================== ;

* Create test dataset;
data work.mactest;
 set sashelp.class (obs=10);

title "Before drops";
proc print data=work.mactest;

%drop_var_if_exists(SASFILE=work.mactest, VAR=name);
%drop_var_if_exists(SASFILE=work.mactest, VAR=xyz);
%drop_var_if_exists(SASFILE=work.mactest, VAR=age);

title "After drops";
proc print data=work.mactest;

* Done ;

Wednesday, October 7, 2015

SAS: Remove carriage return from string

I had a problem with a dataset with a single string field, created using datalines, and the line ended with carriage return + line feed ('0a0d'x), but code was copied to Linux where it was run, and Linux ends its lines with line feed only ('0a'x), so the field contained the carriage return.  I needed to strip the carriage return from the field. I added this line within the data step that created the file.

  my_field = TRANWRD(my_field,'0D'x,'');

SAS: Hash table lookup

SAS hash table lookup example taken from and included in this bog so I can find it easily.

data match;
   length k 8;
   length s 8;
   if _N_ = 1 then do;
      /* load SMALL data set into the hash object */
     declare hash h(dataset: "work.small");
      /* define SMALL data set variable K as key and S as value */
      /* avoid uninitialized variable notes */
      call missing(k, s);

/* use the SET statement to iterate over the LARGE data set using */
/* keys in the LARGE data set to match keys in the hash object */
set large;
rc = h.find();
if (rc = 0) then output;