BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
trungdungtran
Obsidian | Level 7

Hi all,

 

I have a longitudinal data. Each subject is repeatedly measured over time:

 

 

data origin;
	input ID Time;
	cards;
		12	3
		12	5
		12	18
		16	7
		16	25
		16	28
		16	44
	;
run;

 

 

I would like to compute time distance. For the first measurement, time distance is set at 0. From the second time point, time distance is computed by subtracting the previous time from the current time. Time distance is set back to 0 when ID goes to the next one.

 

I have tried a program, it works.

 

proc sort data=origin out=origin_sort;
	by ID Time;
run;

data distance;
	set origin_sort;
	retain distance previous;
	by ID;
	if first.ID=1 then
		do;
			distance=0;
			previous=time;
		end;
	else do;
			distance=Time-previous;
			previous=previous+distance;
		end;
run;

proc print;
run;

I obtain the output as I want.

SAS output.png

 

However, I have to use two variables, and previous is exactly the same as Time.

 

Do you think this is a best way to do or could you suggest some way better?

 

Thank you for reading.

 

P/S: I cannot copy and paste table into this question so I have to use image. I do not know how to use table here. Could you please guide me?

 

1 ACCEPTED SOLUTION

Accepted Solutions
novinosrin
Tourmaline | Level 20
data origin;
	input ID Time;
	cards;
		12	3
		12	5
		12	18
		16	7
		16	25
		16	28
		16	44
	;
run;

data want;
set origin;
by id;
 dist=dif(time);
 if first.id then dist=0;
run;

View solution in original post

3 REPLIES 3
novinosrin
Tourmaline | Level 20
data origin;
	input ID Time;
	cards;
		12	3
		12	5
		12	18
		16	7
		16	25
		16	28
		16	44
	;
run;

data want;
set origin;
by id;
 dist=dif(time);
 if first.id then dist=0;
run;
novinosrin
Tourmaline | Level 20

or 

 

data want;
set origin;
by id;
 dist=ifn(first.id,0,dif(time));
run;
trungdungtran
Obsidian | Level 7
Thank you so much for letting me know a new function in SAS.

Ready to join fellow brilliant minds for the SAS Hackathon?

Build your skills. Make connections. Enjoy creative freedom. Maybe change the world. Registration is now open through August 30th. Visit the SAS Hackathon homepage.

Register today!
Mastering the WHERE Clause in PROC SQL

SAS' Charu Shankar shares her PROC SQL expertise by showing you how to master the WHERE clause using real winter weather data.

Find more tutorials on the SAS Users YouTube channel.

Discussion stats
  • 3 replies
  • 537 views
  • 4 likes
  • 2 in conversation