Victor
Victor

Reputation: 17107

Understanding an implicit loop in SAS data step

I am trying this sample SAS program to understand the DATA step:

DATA WITHOUT_1;
PUT "Before the INPUT statement:  " _ALL_;

INPUT X @@;
PUT "After the INPUT statement:   " _ALL_ /;
DATALINES;
1 2 . 3
;

I did not specify any loops in the program, but how come the PUT statements are logged for each data line?

Where is the implicit loop?

Upvotes: 0

Views: 217

Answers (1)

Quentin
Quentin

Reputation: 6378

The DATA step itself is an implicit loop.

Note that when you run your code the log listing includes the loop counter, _N_.

Your step iterates 5 times because on the 5th iteration, there is no more data to read and it stops:

1    DATA WITHOUT_1;
2    PUT "Before the INPUT statement:  " _ALL_;
3
4    INPUT X @@;
5    PUT "After the INPUT statement:   " _ALL_ /;
6    DATALINES;

Before the INPUT statement:  X=. _ERROR_=0 _N_=1
After the INPUT statement:   X=1 _ERROR_=0 _N_=1

Before the INPUT statement:  X=. _ERROR_=0 _N_=2
After the INPUT statement:   X=2 _ERROR_=0 _N_=2

Before the INPUT statement:  X=. _ERROR_=0 _N_=3
After the INPUT statement:   X=. _ERROR_=0 _N_=3

Before the INPUT statement:  X=. _ERROR_=0 _N_=4
After the INPUT statement:   X=3 _ERROR_=0 _N_=4

Before the INPUT statement:  X=. _ERROR_=0 _N_=5
NOTE: SAS went to a new line when INPUT statement reached past the end of a line.
NOTE: The data set WORK.WITHOUT_1 has 4 observations and 1 variables.

8    ;

Note it is also possible (and sometimes useful) to replace the implicit loop with an explicit loop, e.g.:

DATA WITHOUT_1;
  do i=1 to 4;
    PUT "Before the INPUT statement:  " _ALL_;
    INPUT X @@;
    PUT "After the INPUT statement:   " _ALL_ /;
  end;
  stop;
DATALINES;
1 2 . 3
;

Upvotes: 1

Related Questions