如何使用SAS平均数据集中的最后n个观测值

如何使用SAS平均数据集中的最后n个观测值,sas,Sas,请问,我怎样才能得到数据集中最后6次分组观测的平均值:第一列是分组,即等级,第二列是观测变量,即高度 Class Height 1 12.5 1 14.5 1 15.8 1 16.1 1 18.9 1 21.2 1 23.4 1 25.7 2 13.1 2 15.0 2 15.8 2 16.3 2 17.4 2 18.6 2 22.6 2 24.1 2 25.6 3 11.5 3 12.2 3 13.9 3 14.7 3 18.9 3 20.5 3 21.6 3 22.6 3 24.1 3 25

请问,我怎样才能得到数据集中最后6次分组观测的平均值:第一列是分组,即等级,第二列是观测变量,即高度

Class Height
1 12.5
1 14.5
1 15.8
1 16.1
1 18.9
1 21.2
1 23.4
1 25.7
2 13.1
2 15.0
2 15.8
2 16.3
2 17.4
2 18.6
2 22.6
2 24.1
2 25.6
3 11.5
3 12.2
3 13.9
3 14.7
3 18.9
3 20.5
3 21.6
3 22.6
3 24.1
3 25.8

这有点粗糙,但应该能完成任务。基本上,我们读入数据,然后按行号降序排序。然后,我们可以再次运行数据,并标记每个“类”的前六个观察值。请注意,这仅在您已对“类”上的观察结果进行预排序时有效

* This will read in your data and get a row number;
data one;
input class height;
row_number = _n_;
cards;
1 12.5
1 14.5
1 15.8
1 16.1
1 18.9
1 21.2
1 23.4
1 25.7
2 13.1
2 15.0
2 15.8
2 16.3
2 17.4
2 18.6
2 22.6
2 24.1
2 25.6
3 11.5
3 12.2
3 13.9
3 14.7
3 18.9
3 20.5
3 21.6
3 22.6
3 24.1
3 25.8
;
run;

* Now we sort by row number in descending order;
proc sort data = one out = two;
by descending row_number;
run;

* Now we run through the data again to make a flag for the last
six observations for each class;
data three;
set two;

* This sets up the counter;
retain counter 0;

* This resets the counter to zero at the first instance of each new class;
if class ne lag(class) then counter = 0;

counter = counter + 1;

* This makes a flag (1/0) on whether we want to keep the
observation for analysis;
keep_it = (counter le 6);

run;

* Now we get the means;
proc means data = three mean;
where keep_it gt 0;
class class;
var height;
run;

本例要求输入数据按类排序,每个类至少有6个观察值

data input;
input class height;
cards;
1 12.5
1 14.5
1 15.8
1 16.1
1 18.9
1 21.2
1 23.4
1 25.7
2 13.1
2 15.0
2 15.8
2 16.3
2 17.4
2 18.6
2 22.6
2 24.1
2 25.6
3 11.5
3 12.2
3 13.9
3 14.7
3 18.9
3 20.5
3 21.6
3 22.6
3 24.1
3 25.8
;
run;

data output;
set input;
by class;
average = mean(height, lag1(height), lag2(height), lag3(height), lag4(height), lag5(height));
if last.class;
drop height;
run;

如果输入未按升序/降序排序,而是按类分组(每组中的所有记录“一起”存储,例如序列1、1、3、3、2、2),
NOTSORTED
选项将起作用。

您使用的是SAS(如标题所示)还是SQL Server(如标签所示)?我正在使用SAS进行分析。请显示您尝试过的代码。我可能会添加一个顺序计数器字段,它按组统计每个组中的记录。然后,您可以使用SQL或带有双DoW循环的数据步骤来识别每个by group中的最大计数器,并使用counter>max(counter)-6计算记录的平均值,我不知道该怎么做。我是SASA的初学者,很少想加上最后的x数字。通常会有一些分组因素来确定您的组。这里不是这样吗?还有其他分组变量吗?非常感谢Pablo。我很感激。