如何在SAS数据集中同时选择第一次出现的字段和最后一次出现的另一个字段?


哈哈
2025-03-18 03:26:25 (21天前)


我有一个SAS数据集(按ID分组,Sub_ID按ID排序)如下所示,

ID Sub_ID Field_1 Field_2
1 4 4 8
1 5 9 ……

4 条回复
  1. 0# 一瓶泡沫 | 2019-08-31 10-32



    这是另一个数据步骤解决方案,使用DOW循环而不是保留:




    1. data have;
      input ID Field_1 Field_2 $;
      datalines;
      1 4 8
      1 9 5A
      ;
      run;

    2. data want;
      do until(last.id);
      set have;
      by id;
      if first.id then field_1_1st = field_1;
      end;
      field_1 = field_1_1st;
      drop field_1_1st;
      run;

    3. </code>


    它依次加载每一行,但只输出每个id的最后一行,因此您不必将其作为特殊情况处理。



    注:这只适用于您的输入数据集


    </强>
    包含一个名为的字段

    field_1_1st

    。如果是,则每个id的第一行的值将不会继续。


  2. 1# 至此 | 2019-08-31 10-32



    您需要做的就是将第一个值存储在一个新变量中(使用

    retain

    将语句复制到行中的语句,然后在达到每个ID的最后一个值时输出。
    以下代码将根据数据的当前排序顺序执行此操作。我假设您的真实数据有一​​个额外的变量,可以正确排序数据。




    1. data have;
      input ID Field_1 Field_2 $;
      datalines;
      1 4 8
      1 9 5A
      ;
      run;

    2. data want;
      set have;
      by id;
      retain field_1_1st;
      if first.id then field_1_1st = field_1;
      if last.id then do;
      field_2_last = field_2;
      output;
      end;
      drop field_1 field_2;
      run;

    3. </code>

  3. 2# trpnest | 2019-08-31 10-32



    @longfish的答案是完美的,这只是在SQL中完成的另一种方式。




    1. data have;
      input ID Field_1 Field_2 $;
      datalines;
      1 4 8
      1 5 9
      1 9 5A
      ;

    2. data have1/view=have_1;
      set have;
      val =_n
      ;
      run;

    3. proc sql;
      create table want as
      select id, field_1,
      max(case when Field_2 =(select field_2 from have_1
      group by id having val=max(val))
      then field_2 end) as field_2
      from have_1
      group by id
      having val=min(val);

    4. </code>






登录 后才能参与评论