Creating multiple observations based on multiple other ones

Viewed 47

I am trying to find a way to create observations based on multiple other ones using SAS.

For example, I have the following table:

+------+--------------------+-------------------+
|  ID  |     START_DATE     |     END_DATE      |
+------+--------------------+-------------------+
| ABC1 | 01FEB201500:00:00  | 30NOV201600:00:00 |
| ABC1 | 01JAN201700:00:00  | 30NOV201800:00:00 |
+------+--------------------+-------------------+

And I would like to create a table where all the timestamps for the period 01JAN2014 to 31DEC2020 are covered. In other words, it would consist of creating 2 more observations to the dataset to look like this;

+------+--------------------+-------------------+
|  ID  |     START_DATE     |     END_DATE      |
+------+--------------------+-------------------+
| ABC1 | 01FEB201400:00:00  | 31JAN201500:00:00 |
| ABC1 | 01FEB201500:00:00  | 30NOV201600:00:00 |
| ABC1 | 01DEC201600:00:00  | 30NOV201800:00:00 |
| ABC1 | 01DEC201800:00:00  | 31DEC202000:00:00 |
+------+--------------------+-------------------+

The SAS code to re-create this example is:

DATA test;
INPUT ID :$4. START_DATE :datetime18. END_DATE :datetime18.;
FORMAT START_DATE datetime20. END_DATE datetime20.;
CARDS;
ABC1 01FEB201400:00:00 31JAN201500:00:00
ABC1 01JAN201700:00:00 30NOV201800:00:00
;
RUN;

I don't see a way to do this in SAS

1 Answers

You can fill in (or compute) intra range gaps using basic comparisons, some holding variables and a retained variable.

Example:

Presume no ranges overlap and are order low start first.

data have;
  input id x1 x2; datalines;
1 3 7
1 11 14
2 4 9 
2 15 18
3 1 11
4 11 20
5 1 2
5 3 4
5 5 9
5 10 20
;

data want;
  set have;
  by id;

  length type $6;

  * fill in ranges for every integer 1 through 20;

  if first.id then do;
    bot = 1;
    retain bot;
  end;

  if bot < x1 then do;
    hold1 = x1;
    hold2 = x2;
    x1 = bot;
    x2 = hold1 - 1;
    type = 'gap -';
    output;
    x1 = hold1;
    x2 = hold2;
    type = 'have';
    bot = x2 + 1;
    output;
  end;
  else if x1 <= bot <= x2 then do;
    bot = x2 + 1;
    type = 'have';
    output;
  end;

  if last.id and 20 >= bot > x2 then do;
    type = 'gap +';
    x1 = bot;
    x2 = 20;
    output;
  end;

  keep type id x1 x2 bot;
run;
Related