基于特定索引值存在的条件索引值替换

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

假设有以下内容:


data DB;
  input ID :$20.Date :date9. Index;
  format Date date9.;
cards;
0001 06DEC2016   0
0001 08NOV2020   1
0004 14MAY2015   0
0004 30JUN2015   0
0004 16FEB2019   0
0005 10AUG2019   1
0006 10SEP2014   0
0006 01NOV2015   0
0006 10AUG2021   1
....
;

有办法获得以下内容吗?


data DB1;
  input ID :$20.Date :date9. Index;
  format Date date9.;
cards;
0001 06DEC2016   1
0001 08NOV2020   1
0004 14MAY2015   0
0004 30JUN2015   0
0004 16FEB2019   0
0005 10AUG2019   1
0006 10SEP2014   1
0006 01NOV2015   1
0006 10AUG2021   1
....
;

换句话说:如果某个 ID 的索引列中至少有一个“1”,则对于该 ID(如 ID 0001),索引列中的所有值都应从 0 转换为 1,否则什么也不转换(ID 0004 在 DB 的索引列中只有 0,所以没有任何反应)。

提前谢谢您,

最好

sas
1个回答
0
投票

由于它已经按 ID 排序,因此您可以在索引为 1 的情况下进行基本的自合并:

data want;
    merge db
          db(where=(index=1));
    by id;
run;

如果它们不按顺序排列,并且您想一步完成所有操作,您有两种选择:SQL 和哈希表。

使用 SQL,它看起来像这样:

proc sql;
    create table want as
        select t1.ID
             , t1.Date
             , coalesce(t2.index, t1.index) as index
        from db as t1
        LEFT JOIN
             db(where=(index=1)) as t2
        ON t1.id = t2.id
    ;
quit;

使用哈希表,它看起来像这样:

data want;
    set db;

    if(_N_ = 1) then do;
        dcl hash lookup(dataset: 'db(where=(index=1))');
            lookup.defineKey('id');
            lookup.defineData('index');
        lookup.defineDone();
    end;

    rc = lookup.Find();

    drop rc;
run;
© www.soinside.com 2019 - 2024. All rights reserved.