根据现有变量在 SAS 中创建新观测值

问题描述 投票:0回答:1

我想根据 KEY 变量创建 1 个新观察。对于具有相同 KEY 变量的每组观测值,创建新变量 MASTER,其中新观测值的 MASTER=1。此外,对于具有相同 KEY 变量的每组观测值,如果 AGE、LOCATION、TYPE 完全匹配,则将该数据复制到新观测值。如果不完全匹配,请留空。

我有:

钥匙 年龄 地点 类型
1001 22 XX
1001 22 YY
1006 30 AA
1006 31 AA
1006 30 AA

我想要什么:

钥匙 年龄 地点 类型 大师
1001 22 XX
1001 22 YY
1001 22 1
1006 30 AA
1006 31 AA
1006 30 AA
1006 AA 1
sas
1个回答
0
投票

所以通过KEY设置数据集并使用FIRST./LAST。旗帜。要检查其他变量是否发生变化,您可以使用滞后值。

首先让我们将您的列表转换为实际的 SAS 数据集。

data have;
  input KEY AGE LOCATION $ TYPE $;
cards;
1001 22 XX NEW
1001 22 YY NEW
1006 30 AA OLD
1006 31 AA OLD
1006 30 AA OLD
;

我们可以创建一些保留变量来跟踪是否发生了变化。

data want;
  set have;
  by key ;
  retain many_age many_location many_type;
  lag_age=lag(age);
  lag_location=lag(location);
  lag_type=lag(type);
  if first.key then call missing(of many_:);
  else do;
    many_age+(age ne lag_age);
    many_location+(location ne lag_location);
    many_type+(type ne lag_type);
  end;
  output;
  if last.key then do;
    master=1;
    if many_age then call missing(age);
    if many_location then call missing(location);
    if many_type then call missing(type);
    output;
  end;
  drop lag_: many_: ;
run;

结果

Obs     KEY    AGE    LOCATION    TYPE    master

 1     1001     22       XX       NEW        .
 2     1001     22       YY       NEW        .
 3     1001     22                NEW        1
 4     1006     30       AA       OLD        .
 5     1006     31       AA       OLD        .
 6     1006     30       AA       OLD        .
 7     1006      .       AA       OLD        1
© www.soinside.com 2019 - 2024. All rights reserved.