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!
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;
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;
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
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!
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.