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;
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;
proc summary data=have nway;
class student;
var time;
output out=want(drop=_:) range=Diff;
format time time5.;
run;
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?
It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.
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.
Ready to level-up your skills? Choose your own adventure.