2
votes

Thanks in advance for any help provided. I am trying to "chain" the observation by Type so I can compare successive dates and values on a single observation line. I can do this when I have exactly two observations by Type by using the code below but the issue is I do not know how many observations I will chain for a given type and it is not the write path for this issue.

INPUT:

Obs  Type   Date      Value
1     A     Date_1     19
2     A     Date_2     18
3     A     Date_3     7
4     A     Date_4     3
5     B     Date_1     29
6     B     Date_2     25
7     C     Date_1     29     
.

DESIRED OUTPUT:

Obs  Type   Date       Value    DateB   ValueB
1     A     Date_1     19       Date_2     18
2     A     Date_2     18       Date_3     7
3     A     Date_3     7        Date_4     3
4     B     Date_1     29       Date_2     25
5     C     Date_1     29          NA      NA
.
.

CURRENT CODE for 2 OBS only and for only value (not both date and value):

DATA data_chain; 
 SET data_old; 
 RETAIN LASTREAD; 
 BY Type; 
 IF FIRST.Type THEN LASTREAD = Date;
 ELSE DateB= LASTREAD;  
 DROP LASTREAD;
RUN;
1

1 Answers

1
votes

Easy! Side by side merge with a firstobs=2 copy of itself (which means that you merge obs1 with obs2, obs2 with obs3, etc.), renaming to dateb/valueb. If you want to exactly replicate the above, you need to differentiate between having just one row for a type and having multiple (as you seem to want to treat them differently).

data data_old;
input Obs  Type $ Date  $ Value;
datalines;
1     A     Date_1     19
2     A     Date_2     18
3     A     Date_3     7
4     A     Date_4     3
5     B     Date_1     29
6     B     Date_2     25
7     C     Date_1     29  
;;;;
run;

data data_chain;
merge data_old data_old(rename=(date=dateb value=valueb type=typeb) drop=obs firstobs=2);
if type ne typeb then call missing(of dateb valueb);
run;