问题描述
我想在我的数据集中创建一列,用于计算另一个字段的当前行和下一行的总和.数据中有几个组,如果下一行是当前组的一部分,我只想取下一行的总和.如果一行是该组的最后一条记录,我想用空值填充.
I want to create a column in my dataset that calculates the sum of the current row and next row for another field. There are several groups within the data, and I only want to take the sum of the next row if the next row is part of the current group. If a row is the last record for that group I want to fill with a null value.
我正在引用 在当前观察中读取下一个观察值,但仍然无法弄清楚如何获得我需要的解决方案.
I'm referencing reading next observation's value in current observation, but still can't figure out how to obtain the solution I need.
例如:
data have;
input Group ID Salary;
cards;
10 1 1
10 2 2
10 3 2
10 4 1
11 1 2
11 2 2
11 3 1
11 4 1
;
run;
我想在这里得到的结果是这样的:
The result I want to obtain here is this:
data want;
input Group ID Salary Sum;
cards;
10 1 1 3
10 2 2 4
10 3 2 3
10 4 1 .
11 1 2 4
11 2 2 3
11 3 1 2
11 4 1 .
;
run;
推荐答案
使用 BY 组处理和跳过第一个观察的第二个 SET 语句.
Use BY group processing and a second SET statement that skips the first observation.
data want ;
set have end=eof;
by group ;
if not eof then set have (keep=Salary rename=(Salary=Sum) firstobs=2);
if last.group then Sum=.;
else sum=sum(sum,salary);
run;
这篇关于如何使用SAS按组对下一行的值求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!