Solved
New Contributor
Posts: 3

# Assign value using variable containing names of variables

Hello,

I have a data set with 3 numerical variables A, B and C and 1 character variable V with values "A", "B" or "C". I need to create a numerical variable R that will contain the value of the variable specified in V i.e. if V = "A", then R = value of A. Please see example below:

A    B    C    V     R

1    2     3   "A"    1

1    2     3   "B"    2

4    5     6   "A"    4

4    5     6   "C"    6

I am using SAS 9.3 but for something so simple I guess version is not important.

Thank you very much for your help.

Accepted Solutions
Solution
‎11-22-2017 09:42 AM
Super User
Posts: 10,574

## Re: Assign value using variable containing names of variables

[ Edited ]

Use an array, and the vname() function:

``````data have;
input A    B    C    V \$;
cards;
1    2     3   A
1    2     3   B
4    5     6   A
4    5     6   C
;
run;

data want;
set have;
array vars {*} _numeric_;
do i = 1 to dim(vars);
if vname(vars{i}) = V then R = vars{i};
end;
drop i;
run;``````

PS Note how I posted the dataset (in a data step), and how I used the window for SAS syntax (see https://communities.sas.com/t5/help/faqpage/faq-category-id/posting?nobounce) to post code.

---------------------------------------------------------------------------------------------
Maxims of Maximally Efficient SAS Programmers
How to convert datasets to data steps
How to post code

All Replies
Solution
‎11-22-2017 09:42 AM
Super User
Posts: 10,574

## Re: Assign value using variable containing names of variables

[ Edited ]

Use an array, and the vname() function:

``````data have;
input A    B    C    V \$;
cards;
1    2     3   A
1    2     3   B
4    5     6   A
4    5     6   C
;
run;

data want;
set have;
array vars {*} _numeric_;
do i = 1 to dim(vars);
if vname(vars{i}) = V then R = vars{i};
end;
drop i;
run;``````

PS Note how I posted the dataset (in a data step), and how I used the window for SAS syntax (see https://communities.sas.com/t5/help/faqpage/faq-category-id/posting?nobounce) to post code.

---------------------------------------------------------------------------------------------
Maxims of Maximally Efficient SAS Programmers
How to convert datasets to data steps
How to post code
New Contributor
Posts: 3

## Re: Assign value using variable containing names of variables

Thank you very much for the fast and very useful answer.
SAS Super FREQ
Posts: 508

## Re: Assign value using variable containing names of variables

If your problem is literally that simple, I would do this.  If it is a prototype for something larger, I would write more complicated code involving arrays.

``````data x;
input A B C V \$;
R = ifn(V = 'A', a, ifn(V = 'B', b, c));
datalines;
1    2     3   A
1    2     3   B
4    5     6   A
4    5     6   C
;

proc print; run;``````
New Contributor
Posts: 3