BookmarkSubscribeRSS Feed
lpy0521
Fluorite | Level 6

Hi, there

 

I am curious how to achieve this in SAS. My data is sorted by id and date. for id "a", if the days between date in row 3 and row 4 is equal to 3, then I want to copy var1 to var2. Otherwise, in case id"b", if the days between date in row 3 and row 4 is not equal to 3, then leave it blank. 

 

Thanks in advance!!!

 

data have;
infile cards dlm=',';			
Input ID$ date :ddmmyy10. var1 var2;
format date YYMMDDn8.; 
cards;
a,	01/01/2018,	.	,111,
a,	02/01/2018,	.	,111,
a,	03/01/2018,	.	,111,
a,	06/01/2018,	222	,.,
a,	07/01/2018,	222	,.,
b,	08/01/2018,	.	,111,
b,	09/01/2018,	.	,111,
b,	10/01/2018,	.	,111,
b,	11/01/2018,	222	,.,
b,	12/01/2018,	222	,.,
;			
run;

data want;
infile cards dlm=',';			
Input ID$ date :ddmmyy10. var1 var2;
format date YYMMDDn8.; 
cards;
a,	01/01/2018,	.	,111,
a,	02/01/2018,	.	,111,
a,	03/01/2018,	.	,111,
a,	06/01/2018,	222	,222,
a,	07/01/2018,	222	,.,
b,	08/01/2018,	.	,111,
b,	09/01/2018,	.	,111,
b,	10/01/2018,	.	,111,
b,	11/01/2018,	222	,.,
b,	12/01/2018,	222	,.,
;			
run;


 

2 REPLIES 2
PaigeMiller
Diamond | Level 26
data want;
	set have;
    by id;
	prev_date=lag(date);
	if date-prev_date=3 and not first.id then var2=var1;
    drop prev_date;
run;
--
Paige Miller
novinosrin
Tourmaline | Level 20
data have;
infile cards dlm=',';			
Input ID$ date :ddmmyy10. var1 var2;
format date YYMMDDn8.; 
cards;
a,	01/01/2018,	.	,111,
a,	02/01/2018,	.	,111,
a,	03/01/2018,	.	,111,
a,	06/01/2018,	222	,.,
a,	07/01/2018,	222	,.,
b,	08/01/2018,	.	,111,
b,	09/01/2018,	.	,111,
b,	10/01/2018,	.	,111,
b,	11/01/2018,	222	,.,
b,	12/01/2018,	222	,.,
;			
run;

data want;
do _n_=1 by 1 until(last.id);
set have;
by id;
if _n_=4 and date-lag(date)=3 then var2=var1;
output;
end;
run;

hackathon24-white-horiz.png

The 2025 SAS Hackathon has begun!

It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.

Latest Updates

How to Concatenate Values

Learn how use the CAT functions in SAS to join values from multiple variables into a single value.

Find more tutorials on the SAS Users YouTube channel.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 2 replies
  • 1305 views
  • 1 like
  • 3 in conversation