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.
🙂
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.
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.
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;
Available on demand!
Missed SAS Innovate Las Vegas? Watch all the action for free! View the keynotes, general sessions and 22 breakouts on demand.
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.