考虑以下示例,其中列出了几十名球员
data scores;
input player$ score;
cards;
A 22
A 26
A 38
B 22
B 58
B 60
;
run;
基本上,我想创建两个名为" highscore"的变量。和" lowscore"捕获每个玩家的最高和最低分数。 例如,玩家A的高分为38,玩家B的低分为22。
我尝试了以下代码
data highlow;
set scores;
lowscore=last.score;
highscore=first.score;
run;
它创建了两个变量,但输出不是我想要的。相反,它为每次观察列出了0。
如何使用SAS中的first.
和last.
命令创建这两个变量
答案 0 :(得分:1)
您需要使用by
语句为SAS创建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;
答案 1 :(得分:1)
proc sql的方法。
保留所有记录:
proc sql;
select *, min(score) as lowscore,max(score) as highscore from scores group by player;
quit;
保持低分和高分:
proc sql;
select player, min(score) as lowscore,max(score) as highscore from scores group by player;
quit;
答案 2 :(得分:0)
第一。最后。只存储值为1或0的true或false,即特定值是first.variable还是last.variable。你可以先用。最后。逻辑真和假,然后分配值。你必须按照逻辑分配值如果first.player然后lowscore =得分; 请参阅以下链接以获得更多解释。
http://documentation.sas.com/?docsetId=lrcon&docsetTarget=n01a08zkzy5igbn173zjz82zsi1s.htm&docsetVersion=9.4&locale=en 下面的代码将实现您想要的目标
data scores;
input player$ score;
cards;
A 22
A 26
A 38
B 22
B 58
B 60
;
run;
proc sort data = scores;
by player score ;
run;
data scores1;
set scores;
by player score ;
retain lowscore;
if first.player then lowscore =score;
if last.player then highscore = score;
if last.player then output;
drop score;
run;
data scores_final;
merge scores scores1;
by player;
run;
答案 3 :(得分:0)
您需要先按播放器对数据集进行排序。然后当你设置它时,你应该由玩家添加。您的代码缺少" 按播放器;"线。