title: visitnum for unscheduled visits
body: <p>I am having the following data set: I am trying to assign the visit number for planned and unplanned visits according to the available date.If the date is different then I would like to increment the unplanned visit number (i.e:101.1,101.2). But if the date is same for unplanned visits then I would like to keep the constant visit number across the rows (i.e. 2 or more unplanned visits with same visit number i.e. 101.1,101.1).</p>
  
  <pre><code>    data test;
      infile cards dlm=" ";
      input subject visit event$11. date:date9.;
      format date date9.;
      cards;
      1 1  screening   10oct2017
      1 1  screening   10oct2017
      1 99 unscheduled 10oct2017
      1 99 unscheduled 11oct2017
      1 2  day-1       12oct2017
      1 2  day-1       12oct2017
      1 3  day1        16oct2017
      1 99 unscheduled 15oct2017
      ;
      run;
  </code></pre>
  
  <p>I would like to assign the avisitn as follows:</p>
  
  <pre><code>    1 1  screening   10oct2017   101
      1 1  screening   10oct2017   101
      1 99 unscheduled 10oct2017   101.1
      1 99 unscheduled 11oct2017   101.2
      1 2  day-1       12oct2017   102
      1 2  day-1       12oct2017   102
      1 3  day1        16oct2017   103
      1 99 unscheduled 15oct2017   103.1
  </code></pre>
  
  <p>I have tried to use the following code:</p>
  
  <pre><code>data test;
  infile cards dlm=" ";
  input subject visit event$11. date:date9.;
  format date date9.;
  cards;
  1 1  screening   10oct2017
  1 1  screening   10oct2017
  1 99 unscheduled 10oct2017
  1 99 unscheduled 11oct2017
  1 2  day-1       12oct2017
  1 2  day-1       12oct2017
  1 3  day1        16oct2017
  1 99 unscheduled 15oct2017
  ;
  run;
  
  proc sort data=test;
  by subject date visit;
  run;
  
  data test1;
     set test;
     by subject date visit;
  
     fp = first.subject;
     lp = last.subject;
     fo = first.date;
     lo = last.date;
  run;
  
  data test2;
     set test1;
     by subject date visit;
  
     retain avisitn;
  
     prev_patient_num = lag(subject);
     prev_ordering_date = lag(date);
  
     if visit ne 99 then do;
         if first.subject then avisitn = 101;
         else if subject = prev_patient_num and date ne prev_ordering_date then avisitn + 1;
     end;
  
      if visit eq 99 then do;
          avisitn+0.1;
      end;    
  
     keep subject date visit avisitn;
  run;
  </code></pre>
  
  <p>But, I am getting the following output</p>
  
  <pre><code>subject visit    date     avisitn
  1        1     10OCT2017    101
  1        1     10OCT2017    101
  1       99     10OCT2017    101.1
  1       99     11OCT2017    101.2
  1       2      12OCT2017    102.2
  1       2      12OCT2017    102.2
  1      99      15OCT2017    102.3
  1       3      16OCT2017    103.3
  </code></pre>
  
  <p>Please help me to resolve this. Thanks in advance.</p>