Skip to content

Instantly share code, notes, and snippets.

@statgeek
Created September 24, 2018 19:59
Show Gist options
  • Select an option

  • Save statgeek/e2873910b68d896348ace0917eefd28f to your computer and use it in GitHub Desktop.

Select an option

Save statgeek/e2873910b68d896348ace0917eefd28f to your computer and use it in GitHub Desktop.
SAS - Find value in lookup table that is the minimum distance above your value
/*This finds the nearest value ABOVE a set value, it could be modified to find the lowest or nearest in general
Originally propsed here via F. Khurshed
https://communities.sas.com/t5/SAS-Programming/Finding-Closest-Value-to-a-List-of-Values/m-p/498539
*/
data t1;
input value1;
cards;
31
53
25
125
129
;
data t2;
input value2;
cards;
31
62
93
124
155
;
run;
data find_nearest;
*load data into temporary array;
array _nearest(5) _temporary_;
if _n_=1 then do j=1 to dim(_nearest);
set T2;*dataset with values to load into array;
_nearest(j) = value2;
end;
call sortn(of _nearest(*));
set T1;
do i=1 to dim(_nearest);
if _nearest(i) > value1 then leave;
end;
nearest = _nearest(i);
Difference = _nearest(i) - value1;
keep value1 nearest difference;
run;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment