2
votes

I have a file in which the first line is a header line containing some meta-data information.

How can I get the current observation number(say =1 for the first observation) that the SAS processor is dealing with so that I can put in a IF clause to handle such special data line.

Follow up: I want to process the first line and keep one of the column values in a local variable for further processing. I don't want to keep this line in my final output. is this possible?

2

2 Answers

4
votes

The automatic variable _N_ returns the current iteration number of the SAS data step loop. For a traditional data step, ie:

data something;
set something;
(code);
run;

_N_ is equivalent to the row number (since one row is retrieved for each iteration of the data step loop).

So if you wanted to only do something once, on the first iteration, this would accomplish that:

data something;
set something;
if _n_ = 1 then do;
  (code);
end;
(more code);
run;

For your follow up, you want something like this:

data want;
set have;
retain _temp;
if _n_ = 1 then do;
  _temp = x;
end;
... more code ...
drop _temp;
run;

DROP and RETAIN statements can appear anywhere in the code and have the same effect, I placed them in their human-logical locations. RETAIN says to not reset the variable to missing each time through the data step loop, so you can access it further down.

0
votes

if you are reading a particularly large text file, you may want to avoid having to execute the (if _n_=1 then) condition for every iteration. You can do this by reading the file twice - once to extract the header row, and again to read in the file, as follows:

data _null_; /* create dummy file for demo purposes */
file "c:\myfile.txt";
put 'blah'; output;
put 'blah blah blah 666'; output;

data _null_; /* read in header info */
infile "c:\myfile.txt";
input myvar:$10.; /* or wherever the info is that you need */
call symput('myvar',myvar);/* create macro variable with relevant info */
stop; /* no further processing at this point */

data test; /* read in data FROM SECOND LINE */
infile "c:\myfile.txt" firstobs=2 ; /* note the FIRSTOBS option */
input my $ regular $ input $ statement ;
remember="&myvar";
run;

For short / simple stuff though, Joe's answer is better as it's more readable.. (and may be more efficient for small files).