BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
AnaG_
Calcite | Level 5

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.

🙂

1 ACCEPTED SOLUTION

Accepted Solutions
Kurt_Bremser
Super User

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.

View solution in original post

4 REPLIES 4
Kurt_Bremser
Super User

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.

AnaG_
Calcite | Level 5
Thank you very much for the fast and very useful answer.
WarrenKuhfeld
Ammonite | Level 13

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;
AnaG_
Calcite | Level 5
Thanks a lot, I appreciate it.

SAS Innovate 2025: Register Now

Registration is now open for SAS Innovate 2025 , our biggest and most exciting global event of the year! Join us in Orlando, FL, May 6-9.
Sign up by Dec. 31 to get the 2024 rate of just $495.
Register now!

How to Concatenate Values

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 4 replies
  • 980 views
  • 1 like
  • 3 in conversation