## Variable Name captured in a New Variable

Solved
Occasional Contributor
Posts: 16

# Variable Name captured in a New Variable

Hello,

Don't really know how to describe this but ...

What I'm trying to do is capture which variable output the value to a newly created variable.

data test;

x           = 'ABC123';

P_A     = 4.35;

P_B     = 4.21;

P_C     = 4.01;

run;

data max_extract;

set test;

high = max (of p;

run;

So in this case the high variable would capture 4.35. Can I capture (the variable name, 'P_A') where it came from?

Accepted Solutions
Solution
‎06-18-2013 06:25 AM
Super User
Posts: 10,784

## Re: Variable Name captured in a New Variable

```data test;
x           = 'ABC123';
P_A     = 4.35;
P_B     = 4.21;
P_C     = 4.01;
run;

data max_extract;
set test;
array _x{*} p:;
high = max (of p:);
name=vname(_x{whichn(high,of p:)}) ;

run;

```

Ksharp

All Replies
Super User
Posts: 5,884

## Re: Variable Name captured in a New Variable

Don't know of any (simple) way to do this dynamically. This would involve testing using if-then-else logic, or macro programming.

Another way would be to transpose the table so that your column names (of p will be column values instead, and the use SQL with MAX() and HAVING logic to get your value and name.

Data never sleeps
Occasional Contributor
Posts: 16

## Re: Variable Name captured in a New Variable

Hey Linus,

Thanks for your response! Transpose is prefect for the example but I didn't think it'd be great for the one I'm working with. The IF-THEN-ELSE logic was what I was doing already, just thought there may be a quicker way! Thanks again!

Solution
‎06-18-2013 06:25 AM
Super User
Posts: 10,784

## Re: Variable Name captured in a New Variable

```data test;
x           = 'ABC123';
P_A     = 4.35;
P_B     = 4.21;
P_C     = 4.01;
run;

data max_extract;
set test;
array _x{*} p:;
high = max (of p:);
name=vname(_x{whichn(high,of p:)}) ;

run;

```

Ksharp

Super User
Posts: 5,884

## Re: Variable Name captured in a New Variable

Neat!

Data never sleeps
Occasional Contributor
Posts: 16

## Re: Variable Name captured in a New Variable

Checked it, Loved it! Thanks very much!

Contributor
Posts: 29

## Re: Variable Name captured in a New Variable

Also Try :

data Max_value;

set test;

array max_val

• P:;
•   max_amt=max(of max_val

• );
•   do i=1 to dim(max_val);

if max_val = max_amt then do;

name = vname(max_val);

output;

leave;

end;

end;

/* Keep the variables as desired. */

keep
year name  max_amt;

run;

sunil

Occasional Contributor
Posts: 16

## Re: Variable Name captured in a New Variable

Hey Sunil,

Thanks for replying and thank you for the link to the Array paper!

🔒 This topic is solved and locked.