The SAS hash object has many different applications. Todays topic is no exception. Suppose we want to display all variables in the Program Data Vector (PDV) in a SAS data set. This is not a trivial task. Especially not if we want to do so dynamically. However, the hash object allows us to do so without jumping too many hoops.
The code in this post is based in the article An Application of the SAS® Hash Object by John King (data_null__).
Display All Variables From PDV in SAS Data Set
Consider the SAS code below. The task is this. I want to put all variables from the PDV into a SAS data set. Including first./last., _N_, _I_ and so on. First, I create the variable _pdvname_ variable. This will hold the name of the variable of interest. Then I declare a hash object and define _N_ as the key variable.
Next, I use the Call Vnext Routine. I call the routine as long as it returns a value. Each time Call Vnext is called, the next variable in the PDV appears in _pdvname_. For each call, I use the DefineData Method and define the variable as a data variable in the hash object. This is the technique presented in the blog post Read Many Variables Into the SAS Hash Object.
Next, I read the input data sequentially with the Set Statement. I use the By Statement because I want to display first/last dot variables in the data. Also, I define an implicit array to demonstrate that we even capture the implicit variable _I_.
I add each observation to h. Finally, I use the Ouptut Method on the last iteration of the data step.
options validvarname = any; proc sort data = sashelp.class out = class; by sex age name; run; data _null_; if _N_ = 1 then do; length _pdvname_ $64; declare hash pdvhash(ordered : "Y"); pdvhash.definekey("_N_"); do while (1); call vnext(_pdvname_); if missing(_pdvname_) then leave; if _pdvname_ = "_pdvname_" then continue; pdvhash.definedata(_pdvname_); end; pdvhash.definedone(); end; set class(in = inClass) end = end nobs = nobs; by sex age name; array a sex; pdvhash.add(); if end then do; pdvhash.output(dataset : "AllVarsInPDV"); stop; end; run; proc print;run;
Check the AllVarsInPDV data set. ALL variables from the PDV and their values are in the data.
In this post, I demonstrate how to display all variables and their values from the PDV in a SAS data set. It is not a trivial task to do so dynamically. However, a combination of the hash object and traversing the PDV with the Call Vnext Routine lets us do so swiftly.
You can download the entire code from this post here.