title: How to find the previous value of a variable in SAS
body: <p>I am trying to populate a variable with set conditions. </p>
  
  <p>If the variable NUMBER is equal to . then make it equal to the previous value of Number.</p>
  
  <pre><code>data table2;
    set table1;
  
    prv_value = lag(number);
    if number = . then number = prv_value;
  run;
  </code></pre>
  
  <p>However, if there are two values in a row where number = . then the second occurrence of the value of . has it's previous value of number = . .</p>
  
  <p>What I would like is to find the first previous occurrence where number is not equal to . and make the value of number equal to that previous non-missing value. </p>
  
  <p>An example of my data is:</p>
  
  <pre><code>id  number
  d10   2       
  d10   2       
  d10   3       
  d10   .       
  d10   .       
  </code></pre>
  
  <p>Applying the above code I would then get:</p>
  
  <pre><code>id  number prv_number
  d10   2       .
  d10   2       2
  d10   3       2
  d10   3       3
  d10   .       .
  </code></pre>
  
  <p>What I would like is:</p>
  
  <pre><code>id  number prv_number
  d10   2       .
  d10   2       2
  d10   3       2
  d10   3       3
  d10   3       .
  </code></pre>
  
  <p>i.e. if number has a value of . then make it equal to the first previous occurrence of a non-missing value.</p>
  
  <p>In some cases in my dataset I might have:</p>
  
  <pre><code>id  number
  d10   4
  d10   2
  d10   .
  d10   .
  d10   .
  d10   .
  </code></pre>
  
  <p>and what I would like is:</p>
  
  <pre><code>id  number
  d10   4
  d10   2
  d10   2
  d10   2
  d10   2
  d10   2
  </code></pre>
  
  <p>(Note, my data is sorted in order of events/time, hence wanting the first previous occurence).</p>
  
  <p>Is there anything I can do with the lag function over different number of previous occurrences, or anything else that can do what I'd like?</p>