DATA Step, Macro, Functions and more

Minimum of prior values

Accepted Solution Solved
Reply
Contributor
Posts: 30
Accepted Solution

Minimum of prior values

If I have a set of values ordered by ID and date, how do I determine the minimum value for each record at from all prior dates? I've tried using RETAIN but don't seem to be obtaining the correct results.


Accepted Solutions
Solution
‎09-19-2017 10:43 AM
Super User
Posts: 5,518

Re: Minimum of prior values

Here's an approach that assumes you do NOT want the current value considered when computing the PRIOR minimum:

 

proc sort data=have;

by id date;

run;

 

data want;

set have;

by id date;

if first.id then min_val = .;

retain min_val;

output;

min_val = min(min_val, varname);

run;

View solution in original post


All Replies
Solution
‎09-19-2017 10:43 AM
Super User
Posts: 5,518

Re: Minimum of prior values

Here's an approach that assumes you do NOT want the current value considered when computing the PRIOR minimum:

 

proc sort data=have;

by id date;

run;

 

data want;

set have;

by id date;

if first.id then min_val = .;

retain min_val;

output;

min_val = min(min_val, varname);

run;

Contributor
Posts: 30

Re: Minimum of prior values

Posted in reply to Astounding

This method works well for what I'm doing. Any variations for when missing values appear in the series?

Super User
Posts: 5,518

Re: Minimum of prior values

The MIN function ignores missing values.  So I'm assuming you would like to add the possibility that the calculated minimum value comes out missing if one of the incoming values is missing.  That's slightly harder but not a great deal different.  After sorting:

 

data want;

set have;

by id date;

retain min_val;

if first.id then do;

   min_val = .;

   output;

   min_val = 1e17;

end;

else output;

if varname < min_val then min_val = varname;

run;

☑ This topic is solved.

Need further help from the community? Please ask a new question.

Discussion stats
  • 3 replies
  • 123 views
  • 0 likes
  • 2 in conversation