Help using Base SAS procedures

Maximum Variable

Reply
N/A
Posts: 0

Maximum Variable

Hi

I have a list of 8 variables and want to find the largest variable for each record.
For example if my data looked like this:
Key age1 age2 age3 age4
001 0.5 0.6 0.7 0.3
002 0.8 1.7 1.2 4.6
I would like to create a variable that looks like this:
Key age1 age2 age3 age4 maxv
001 0.5 0.6 0.7 0.3 age3
002 0.8 1.7 1.2 4.6 age4

Anyone know how I could do this, or something similar?
Esteemed Advisor
Posts: 5,155

Re: Maximum Variable

Hi,
try the MAX-function (in a data step):

maxv = max(age1, age2, age3, age4); or in your specific case with a variable list:
maxv = max(of age1-age4);

Regards,
Linus
Data never sleeps
N/A
Posts: 0

Re: Maximum Variable

thanks Linus, this gave me the value of the maximum variable, whereas I was after the variable name, however I will definitely use this in the future!
Super Contributor
Super Contributor
Posts: 3,174

Re: Maximum Variable

One technique is to use a SAS macro variable to identify/track the age values, presuming the data sample you provided. Here's some SAS code that works.

Scott Barry
SBBWorks, Inc.

%let ages = age1 age2 age3 age4;
data _null_;
input Key $ &ages;
* use array to interrogate age# var list for max. ;
array _agevars (*) &ages ;
do i=1 to dim(_agevars);
if _agevars(i) gt _maxval then do;
drop _maxval;
* keep track of the max var-value thus far. ;
_maxval = _agevars(i);
* keep track of the var-name having max value thus far. ;
maxv = upcase(scan("&ages",i,' '));
end;
end;
putlog _all_;
datalines;
001 0.5 0.6 0.7 0.3
002 0.8 1.7 1.2 4.6
run;
N/A
Posts: 0

Re: Maximum Variable

thank you Scott that worked perfectly
N/A
Posts: 0

Re: Maximum Variable

you can use the function varname and varnum combine with macro to do that
N/A
Posts: 0

Re: Maximum Variable

use these two function you do not need to know the variname, only do loop on the variable number, but be ware that you should use %sysfun in the macro enviroment
Super Contributor
Posts: 260

Re: Maximum Variable

Hi.
What seems to me a simpler solution -- no macros needed, just use the VNAME function.
[pre]
data out (drop = i max_age) ;
set in ;
array ages age: ;
max_age=MAX(OF ageSmiley Happy ;
do i=1 TO DIM(ages) ;
if ages(i) = max_age then maxv=VNAME(ages(i)) ;
end ;
run ;
[/pre]
Regards,
Olivier
Super Contributor
Super Contributor
Posts: 3,174

Re: Maximum Variable

Very clean, Olivier. The VNAME function had escaped me and so I used the macro variable (parsing) approach. Thanks for the great tip!

Regards,

Scott Barry
SBBWorks, Inc.
Ask a Question
Discussion stats
  • 8 replies
  • 141 views
  • 0 likes
  • 4 in conversation