Looping through SAS Rows

I'm fairly new to SAS, (I mainly use R, Python, and VBA) and I am looking for a way to loop through the rows of a SAS data set. Essentially, the R equivalent would be:

my_vector = c()
for(k in 1:10) {
if(k > 1 & k < 10) {
   my_vector[k-1] = mean(df[(k-1):(k+1), 1])
{
}

My main goal is to create an MA filter to estimate trend (I could do my homework in R, but I'm trying to learn SAS better).

Or, another solution would be to convert a specific row of a SAS data set into an array from PROC IML but I can't figure out how to get the column converted into an array.

Any help would be greatly appreciated.

Upvotes: 0

Views: 3170

Answers (2)

Drew
Drew

Reputation: 21

There are some pitfalls with the LAG function as per this article

If you are having trouble with it, use PROC TRANSPOSE to pivot your data and process as an array, comparing columns (if var_1 = 'YES' and var_2 = 'YES' then new_var = 'BLUE'), or manually create an array which might be more advanced than you want right now.

Upvotes: 1

Rob
Rob

Reputation: 31

From what I understand, your looking for a way to look back and also look ahead of the current row. If that is correct then the main solution is the lag() function. This looks back on what ever variable you place within the lag() function. It can also go back multiple rows lag2() lag3(). Additionaly the dataset needs to be sorted by the laged variable. Now looking ahead is tricky, no function is available for this, but you can use multiple set statements to accomplish this goal.

Here is an example of the looking ahead from Mark Keintz's paper

 data lead_example5;
     set sample1;

     if eof1=0 then
          set sample1 (firstobs=2 keep=close rename=(close=LEAD1)) end=eof1;
     else lead1=.;

    if eof3=0 then
         set sample1 (firstobs=4 keep=close rename=(close=LEAD3)) end=eof3;
    else lead3=.;
 run;

Also here is an example of the lag() function also from

data example1;
    set sample1;

    close_1=lag(close);
    close_3=lag3(close);

    if close_1 ^=. then return_1 = close/close_1 - 1;
    if close_2 ^=. then return_3 = close/close_3 - 1;
run;

Upvotes: 0

Related Questions