下面是在SAS中从数据集中选择前N行的两种最常见的方法。
方法1:选择第一行
data first_row;
set original_data;
if _N_ = 1 then output;
run;
方法2:选择前N行
data first_N_rows;
set original_data;
if _N_ <= 5 then output; /*select first 5 rows*/
run;
下面的例子展示了如何在SAS中用以下数据集来使用每种方法:
/*create dataset*/
data original_data;
input team $ points rebounds;
datalines;
Warriors 25 8
Wizards 18 12
Rockets 22 6
Celtics 24 11
Thunder 27 14
Spurs 33 19
Nets 31 20
Mavericks 34 10
Kings 22 11
Pelicans 39 23
;
run;
/*view dataset*/
proc print data=original_data;
例子1:选择第一行
下面的代码显示了如何只选择数据集的第一行。
/*create new dataset that contains only the first row*/
data first_row;
set original_data;
if _N_ = 1 then output;
run;
/*view new dataset*/
proc print data=first_row;
我们可以看到,新的数据集只包含原数据集的第一行。
例2:选择前N行
下面的代码显示了如何选择数据集的前五行:
/*create new dataset that contains first 5 rows of original dataset*/
data first_N_rows;
set original_data;
if _N_ <= 5 then output;
run;
/*view new dataset*/
proc print data=first_N_rows;
我们可以看到,新的数据集只包含了原始数据集的前五行。
要选择不同数量的起始行,只需改变上面代码中_N_后面的值。
其他资源
下面的教程解释了如何在SAS中执行其他常见任务:
如何在SAS中使用Proc Summary
如何在SAS中使用Proc Tabulate
如何在SAS中重命名变量
如何在SAS中创建新变量