Read previous and next observations

前端 未结 2 922
一生所求
一生所求 2021-01-13 03:28

I have a dataset like this(sp is an indicator):

datetime        sp
ddmmyy:10:30:00 N
ddmmyy:10:31:00 N
ddmmyy:10:32:00 Y
ddmmyy:10:33:00 N
ddmmyy:10:34:00 N
         


        
相关标签:
2条回答
  • 2021-01-13 03:48

    Try using the point option in set statement in data step. Like this:

    data extract;
    set surprise_6_step2 nobs=nobs;
    if sp = 'Y' then do;
      current = _N_;
      prev = current - 1;
      next = current + 1;
    
      if prev > 0 then do;
        set x point = prev;
        output;
      end;
    
      set x point = current;
      output;
    
      if next <= nobs then do;
        set x point = next;
        output;
      end;
    end;
    
    run;
    

    There is an implicite loop through dataset when you use it in set statement. _N_ is an automatic variable that contains information about what observation is implicite loop on (starts from 1). When you find your value, you store the value of _N_ into variable current so you know on which row you have found it. nobs is total number of observations in a dataset.

    Checking if prev is greater then 0 and if next is less then nobs avoids an error if your row is first in a dataset (then there is no previous row) and if your row is last in a dataset (then there is no next row).

    0 讨论(0)
  • 2021-01-13 04:05
    /* generate test data */
    data test;
        do dt = 1 to 100;
            sp = ifc( rand("uniform") > 0.75, "Y", "N" );
            output;
        end;
    run;
    
    proc sql;
        create table test2 as
            select  *,
                monotonic() as _n
            from  test
        ;
        create table test3 ( drop= _n ) as
            select  a.*
            from    test2 as a
            full join   test2 as b
                on  a._n = b._n + 1
            full join   test2 as c
                on a._n = c._n - 1
            where   a.sp = "Y"
                or b.sp = "Y"
                or c.sp = "Y"
        ;
    quit;
    
    0 讨论(0)
提交回复
热议问题