DATA Step, Macro, Functions and more

Using Lag Properly

Not applicable
Posts: 0

Using Lag Properly


I have the following data:
input_table (ordered by customernumber, code number):

customernumber code_number

1 a1
1 b1
1 c1
2 a1
2 c1
3 c1

I'd like to use lag to look 2 rows prior, determine if the customernumber is the same for the prior 2 customernumber rows, then look at the code number, and determine if I'm on code number c1, and if so look back at the 2 prior code number rows are a1 and b1. If so, this meets the criteria I'm looking for. As an example, customernumber 1 is the only one above that matches this criteria. I'm using the following SAS code to do this, using lag. Please let me know if this looks good, thx!

libname sassvrtable 'my/sasdatabase/table'
data output_data;
set sassvrtable.input_table;

\*prev custnumber*\
lag_data_custnum = lag(customernumber);

\*2nd prev custnumber*\
lag_data_custnum2 = lag(lag_data_custnum);

\*prev codenumber*\
lag_code_number = lag(code_number);
\*2 prev codenumber*\
lag_code_number_2 = lag(lag_code_number);

if lag_data_custnum = customernumber
and lag_data_custnum2 = customernumber
and code_number = c1
and lag_code_number = b1
and lag_code_number_2 = a1
then match = 'TRUE';

Proc Print data = output_data;
Super Contributor
Posts: 339

Re: Using Lag Properly

Posted in reply to deleted_user
Hi Scott,

Try using lag2 instead of lag

Not applicable
Posts: 0

Re: Using Lag Properly

Thank you, this will work.
Ask a Question
Discussion stats
  • 2 replies
  • 2 in conversation