DATA Step, Macro, Functions and more

Inserting a datastep variable value within another variable name

Accepted Solution Solved
Reply
Contributor
Posts: 38
Accepted Solution

Inserting a datastep variable value within another variable name

[ Edited ]

Hello, I have a simple problem I would apprecieate any help with.

 

Suppose in my dataset I have a variable called TYPE which is A, B, C, or D. Furthermore I have four additional variable xA, xB, xC, xD. What I would like to do is create a new variable x that has the appropriate xA, xB, etc value depending on the TYPE. So if TYPE=A then x=xA, etc. Here is an example table;

 

TYPE xA xB xC xD x
A 1 3 0 2 1
D 0 9 5 3 3
C 4 2 0 0 0

 

 

I've tried x=x||TYPE and call execute('x=x'||TYPE||';'); but to no avail. I read that you can use some combination of symput and symget.

 

At worst I can do if TYPE='A' then x=XA, etc. but this is really inefficent code (I have 20 different TYPE letters).

 

Is there an elegant solution for this?

 

Thank you!


Accepted Solutions
Solution
‎04-09-2016 12:58 PM
Super User
Posts: 17,784

Re: Inserting a datastep variable value within another variable name

VVALUEX function is what you're after. It returns it as a character though, so you need to convert it to numeric, if required.

 

 

x=vvaluex("x"|Type);
data want;
input type $ xA xB xC xD;
x=vvaluex("x"||type);
cards;
A 1 3 0 2
D 0 9 5 3
C 4 2 0 0 
;
run;

View solution in original post


All Replies
Solution
‎04-09-2016 12:58 PM
Super User
Posts: 17,784

Re: Inserting a datastep variable value within another variable name

VVALUEX function is what you're after. It returns it as a character though, so you need to convert it to numeric, if required.

 

 

x=vvaluex("x"|Type);
data want;
input type $ xA xB xC xD;
x=vvaluex("x"||type);
cards;
A 1 3 0 2
D 0 9 5 3
C 4 2 0 0 
;
run;
Super Contributor
Posts: 408

Re: Inserting a datastep variable value within another variable name

This seems like an excellent oppportunity to use arrays. Image to arrays, one temporary with 'A', 'B', etc. The other one with XA, XB, ...

The loop up the index of TYPE in the first and use that index to assign  the value of X to the variable in the second array with the found index.

 

data want;
    array types[4] $ _temporary_  ('A' 'B' 'C' 'D');
    array xs[*] xa xb xc xd;
    type='D';
    x=100;
    do i=1 to dim(types);
      if type=types[i] then xs[i]=x;
    end;
    put _all_;
run;

Hope this gets you on your way,

- Jan

Super Contributor
Posts: 408

Re: Inserting a datastep variable value within another variable name

Oh rats. I did it the other way round. Looks like @Reeza has the proper solution. Smiley Happy

 

- Jan.

☑ This topic is SOLVED.

Need further help from the community? Please ask a new question.

Discussion stats
  • 3 replies
  • 239 views
  • 0 likes
  • 3 in conversation