How to find the previous value of a variable in SAS

I am trying to populate a variable with given conditions.

If the variable NUMBER is equal. then make it equal to the previous Number value.

data table2; set table1; prv_value = lag(number); if number = . then number = prv_value; run; 

However, if the line has two values, where number =. then the second occurrence of the value. has this previous value of number = ..

I would like to find the first previous occurrence where the number is not equal. and make the value of the number equal to the previous missing value.

An example of my data is:

 id number d10 2 d10 2 d10 3 d10 . d10 . 

Using the code above, I would get:

 id number prv_number d10 2 . d10 2 2 d10 3 2 d10 3 3 d10 . . 

I would like to:

 id number prv_number d10 2 . d10 2 2 d10 3 2 d10 3 3 d10 3 . 

i.e. if the number matters. then make it equal to the first previous entry of the missing value.

In some cases, in my dataset, I could:

 id number d10 4 d10 2 d10 . d10 . d10 . d10 . 

and I would like to:

 id number d10 4 d10 2 d10 2 d10 2 d10 2 d10 2 

(Note: my data is sorted by event / time order, so the first previous occurrence is required).

Is there anything I can do with the delay function in different numbers of previous events, or anything else that can do what I wanted?

+4
source share
1 answer

You can try using the save statement as follows (untested):

 data table2; set table1; retain prv_value .; if number=. then number=prv_value; if number ne . then prv_value=number; run; 

Regards, Amir.

+6
source

All Articles