SAS (Base SAS)+
*=============================================================================;
* Create the input dataset;
*=============================================================================;
data fs;
input usubjid visitnum score;
datalines;
101 1 20
101 2 10
101 3 30
102 1 90
102 2 10
102 3 100
;
run;
*=============================================================================;
* Sort the dataset by usubjid and visitnum;
*=============================================================================;
proc sort data=fs;
by usubjid visitnum;
run;
*=============================================================================;
*Retain the first score onto all records;
*=============================================================================;
data fs01;
set fs;
by usubjid visitnum;
retain first_score;
if first.usubjid then first_score = score;
run;- To carry the first score of each subject forward onto every record, we sort by subject and visit, then use
RETAINwithfirst.usubjid. - SAS uses BY-group processing: after
PROC SORTbyusubjid visitnumand abystatement in the DATA step, SAS exposes automatic flagsfirst.usubjidandlast.usubjid. retain first_score;tells SAS not to resetfirst_scoreto missing at the start of each row — it holds whatever value we assigned on the previous row.if first.usubjid then first_score = score;captures the score from the very first row of each subject. Because of the retain, that value stays in place for every subsequent row of the same subject.- After running, we expect
fs01to have all six input rows plus a newfirst_scorecolumn equal to the first visit’s score within each subject.