BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
Shradha1
Obsidian | Level 7
I have a data set for students and various time points.
Student time
A 12:10
A 12:11
A 12:20
A 12:45
B 3:10
B 3:16
B 3:32
C 8:05
C 8:54
C 9:10
I want the difference between the first and last observation for a particular student. I want the result as
A 00:35
B 00:22
C 00:55

How do I do this?
1 ACCEPTED SOLUTION

Accepted Solutions
novinosrin
Tourmaline | Level 20

data have;
input Student $ time :time.;
format time time.;
cards;
A 12:10
A 12:11
A 12:20
A 12:45
B 3:10
B 3:16
B 3:32
C 8:05
C 8:54
C 9:10
;

proc sql;
 create table want as
 select student, range(time) as diff format=time5.
 from have
 group by student;
quit;

View solution in original post

3 REPLIES 3
novinosrin
Tourmaline | Level 20

data have;
input Student $ time :time.;
format time time.;
cards;
A 12:10
A 12:11
A 12:20
A 12:45
B 3:10
B 3:16
B 3:32
C 8:05
C 8:54
C 9:10
;

proc sql;
 create table want as
 select student, range(time) as diff format=time5.
 from have
 group by student;
quit;

novinosrin
Tourmaline | Level 20

proc summary data=have nway;
 class student;
 var time;
 output out=want(drop=_:) range=Diff;
 format time time5.;
run;
Reeza
Super User

Use BY group processing with FIRST and LAST and RETAIN.

 

data want;
set have;

by Student; *may require presorting to have sorted by student;

*holds value across the rows as you go down;
retain start_time;
*assigns the time to a new variable, start_time;
if first.Student then start_time = time;

*if last record for a student then calculate the duration and output the record;
if last.student then do;
      duration = time - start_time;
      output;
end;

run;

Alternatively, if you know that the smallest time is always the start and the largest time is always the end then you can use the RANGE option from PROC MEANS.

 

proc means data=have RANGE noprint;
class Student;
var time;
output out=want range = duration;
run;

proc print data=want;
var student duration;
format duration time.;
run;

@Shradha1 wrote:
I have a data set for students and various time points.
Student time
A 12:10
A 12:11
A 12:20
A 12:45
B 3:10
B 3:16
B 3:32
C 8:05
C 8:54
C 9:10
I want the difference between the first and last observation for a particular student. I want the result as
A 00:35
B 00:22
C 00:55

How do I do this?

 

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
  • 3 replies
  • 753 views
  • 2 likes
  • 3 in conversation