Help using Base SAS procedures

Idenfitying variable with the lowest/highest values

Reply
Contributor
Posts: 58

Idenfitying variable with the lowest/highest values

I have this sample dataset and want to identify the variable with either the highest or lowest value. So in this case not to report the value but report the variable. Does anyone have any suggestions on how to do this?

IDVar1Var2Var3WANT_LowestWANT_Highest
1205030Var1Var2
20.900.250.10Var3Var1

So I want these two variables. As we can see with ID=1, the highest value is Var2 so the WANT_highest is coded Var2.  Similaringly with the lowest for Var1.

What is the easiest way to do this? I know the max/min function will return the values. But in this case I want it to return the variable name.

Super User
Super User
Posts: 7,942

Re: Idenfitying variable with the lowest/highest values

Hi,

Sorry, let me re-do that, I see you don't want the value.  I would transpose, then you can do normal min/max:

data have;

  id=1; var1=20; var2=50; var3=30; output;

run;

proc transpose data=have out=want;

  by id;

  var var1-var3;

run;

Arrays are probably the easiest:
data want;

     set have;

     array var{3};

     want_lowest=min(of var{*});

     want_highest=max(of var{*});

run;

PROC Star
Posts: 7,468

Re: Idenfitying variable with the lowest/highest values

data want;

  set have;

  array arr

  • Var1--Var3;
  •   length WANT_Lowest WANT_Highest $32;

      WANT_Lowest = vname(arr[whichn(min(of arr

  • ), of arr
  • )]);
  •   WANT_Highest = vname(arr[whichn(max(of arr

  • ), of arr
  • )]);
  • run;

    Super Contributor
    Posts: 308

    Re: Idenfitying variable with the lowest/highest values

    hello,

    data have;
    input ID Var1 Var2 Var3  ;
    datalines;
    1 20 50 30
    2 0.90 0.25 0.10
    ;
    run;

    data want;
    set have;
    array vars{*} var1-var3;
    max_val=max(var1, var2,var3);
    min_val=min(var1, var2,var3);

    do i=1 to dim(vars) until(vars{i}=max_val);
    WANT_Highest=vname(vars{i});
    end;


    do i=1 to dim(vars) until(vars{i}=min_val);
    WANT_Lowest=vname(vars{i});
    end;

    drop max_val min_val i;
    run;

    Ask a Question
    Discussion stats
    • 3 replies
    • 477 views
    • 1 like
    • 4 in conversation