reading next observation's value in current observation

后端 未结 3 1168
梦如初夏
梦如初夏 2020-12-08 12:26

I\'ve a dataset called \'input\' with the following observations

ID Salary
10 1000
20 2000
30 3000
40 4000

I need an output dataset with

相关标签:
3条回答
  • 2020-12-08 12:48

    There are a few ways to achieve this, here's how I would do it.

    data have;
       input ID Salary;
       cards;
    10 1000
    20 2000
    30 3000
    40 4000
    ;
    run;
    
    data want;
       recno=_n_+1;
       set have end=last;
       if not last 
               then set have (keep=salary rename=(salary=next_row_salary)) point=recno;
          else call missing(next_row_salary);
    run;
    
    0 讨论(0)
  • 2020-12-08 12:51

    There's no direct way to do this in a data step. There's two approaches you can use:

    Option 1: Sort in reverse, use the lag function

    proc sort data=your_dataset;
     by descending id;
    run;
    
    data your_dataset;
     set your_dataset;
     next_row_salary = lag(salary);
    run;
    
    proc sort; by id; run;
    

    Options 2: Use proc expand

    proc expand data=your_dataset method=none;
     by id;
     convert salary = next_row_salary / transformout=(lead 1);
    run;
    
    0 讨论(0)
  • 2020-12-08 13:11

    This code is from Paul Dorfman on SAS-L and it does what you are looking for as well with one pass through the data

    Data Salary;
    input id salary;
    Datalines;
    10 1000
    20 2000
    30 3000
    40 4000
    ;
    Run;
    
    data need ;
    retain id salary;
    set salary (rename=(id = origid salary=next_salary)) end=end ;
    if _n_ > 1 then output;
    salary = next_salary;
    id = origid;
    if not end then return;
    call missing(next_salary);
    output;
    drop origid;
    run ;
    
    0 讨论(0)
提交回复
热议问题