DATA Step, Macro, Functions and more

Copy value from next observation

Reply
Frequent Contributor
Frequent Contributor
Posts: 101

Copy value from next observation

[ Edited ]
 
Super User
Super User
Posts: 7,401

Re: Copy value from next observation

Hi,

 

Well, you can hold the data over with retain, and then control the output using output statement as given below.  However I would advise you to get more ata there to help.  As it stands with what you have provided there is not enough information to do this properly, i.e. a change in sort alters that data completely.  Normally on these type of questions you would reverse sort the data, then retain last value, much simpler and robust.  So get something in the data which indicates the order and make your life easier.

data have;
  input id d value;
datalines;
1 1 80
1 0 100
1 1 100
1 0 120
1 1 30
1 0 50
;
run;

data want;
  set have end=last;
  retain out_id out_d out_value;
  if _n_=1 then do;
    out_id=id;
    out_d=d;
    out_value=value;
  end;
  else do;
    if d=0 and out_d=1 then do;
      out_value=value;
      output;
    end;
    else output;
  end;
  if last then output;
run;
Frequent Contributor
Frequent Contributor
Posts: 101

Re: Copy value from next observation

Thanks RW. Yes reverse sorting and retaining is the best solution.
Frequent Contributor
Posts: 103

Re: Copy value from next observation

[ Edited ]
data hlp1;
   set have;
   retain hlp_group;
   if mod(_N_,2) then hlp_group+1;
run;
proc sort data=hlp1 out=hlp2; by hlp_group id d; run;

data hlp3;
   set hlp2;
   by hlp_group id d;
   hlp_lag1_value=lag1(value);
   if not first.hlp_group then value=hlp_lag1_value;
run;

PROC SORT DATA=hlp3 out=want(keep=id d value); by hlp_group id descending d;run;
________________________

- That still only counts as one -

Ask a Question
Discussion stats
  • 3 replies
  • 146 views
  • 0 likes
  • 3 in conversation