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
Rhodochrosite | Level 12

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-2024.png

Available on demand!

Missed SAS Innovate Las Vegas? Watch all the action for free! View the keynotes, general sessions and 22 breakouts on demand.

 

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.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

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