您需要为 SAS 使用 by 语句来创建 first. 和 last. 变量。但它们不采用 by 变量的值,它们只是布尔标志,用于指示您是否在第一次(或最后一次)观察 BY 变量的这个特定值。
如果您只想找到最小值和最大值,并且您的值已经排序,那么这很简单。
data want ;
set scores;
by player score ;
if first.player then lowscore=score ;
retain lowscore ;
if last.player ;
highscore=score ;
keep player lowscore highscore ;
run;
请注意,您需要保留 lowscore 变量,以便在数据步移至下一个观察值时不会清除在第一个观察值上设置的值。您可以通过在 SET 语句周围使用 DO 循环来避免对 RETAIN 的需要。
data want ;
do until (last.player);
set scores;
by player score ;
if first.player then lowscore=score ;
highscore=score ;
end;
keep player lowscore highscore ;
run;
如果数据是按玩家排序的,而不是按玩家和得分排序的,那么您需要添加更多逻辑来查找最小值和最大值。
data want ;
do until (last.player);
set scores;
by player ;
lowscore=min(lowscore,score);
highscore=max(highscore,score);
end;
keep player lowscore highscore ;
run;
如果您还想保留所有原始观察结果,请添加另一个 DO 循环以重新读取数据并输出详细信息行。
data want ;
do until (last.player);
set scores;
by player ;
lowscore=min(lowscore,score);
highscore=max(highscore,score);
end;
do until (last.player);
set scores;
by player ;
output;
end;
run;