Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Can I use lag

Status
Not open for further replies.

MARINO1982

Technical User
Feb 13, 2009
2
CA
Hello there,

i'm new to SAS, as my organization recently switched from SPSS. Currently i've been able to do everything in SAS that i did in SPSS except for this.

For the sake of simplicity, let say i have sorted column 1 for which i took a subset and the corresponding column 2 of data attributed to it. I want to transform column 2 to compute column 3 (i.e where there is a zero i want the last non-zero preceeeding value). Now this could be done with the lag function if there was only one 0 following each non-zero value, however, as you can see there are cases with 'n' zero values follwing the non-zero. I can't use lagn either, because there may be cases where if i use LAG3, it will look too far back and pull the wrong non zero value.

a 1 1
a 0 1
a 2 2
a 0 2
a 0 2
a 3 3
a 0 3
a 0 3
a 0 3
4 4 4

I am DESPERATE for help on how to program SAS to accomplish this. Any help would be greatly appreciated!

Marino

 
Hi Marino,

I think you are looking for the retain statement instead of the lag function.

The retain statement tells SAS not to re-initialise a variable in the PDV.

You haven't mentioned on how to handle cases where there is a zero as the first record for each of the column 1 groups. I presume, you want to treat each group as separate entities, and not continue over group boundaries. I've modified your test data to demonstrate this.

Code:
data have ;
   input id :$1. valA ;
   cards ;
a  1   
a  0   
a  2   
a  0   
b  0   
b  3   
b  0   
b  0   
b  0   
;
data want ;
   retain valB ;
   set have ;
   by id ;
   if first.id or valA then valB = valA ;
   run ;
proc print ; 
   run ;

output:
Code:
    Obs    valB    id    valA

     1       1     a       1
     2       1     a       0
     3       2     a       2
     4       2     a       0
     5       0     b       0
     6       3     b       3
     7       3     b       0
     8       3     b       0
     9       3     b       0

 
thanks so much!

after seeing your reply and reading up on the retain statement, i think this should pretty much do it!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top