Hello,
I am trying to create a macro variable to add a new column. There are 15 primary columns (primary1-primary15) and i want to make a new variable called "Code" that has "tax-" and then the same number as in the primary variable. See example:
if primary1= "Y" then Code=tax1;
if primary2= "Y" then Code=tax2;
if primary3= "Y" then Code=tax3;
... up until if primary15="Y" then Code=tax15
Can someone help me please?
Not sure what your question has to do with macro variables. Looks like you are checking actual variables. In that case you just need to use an array.
Since the way you wrote the series of IF statement the test of PRIMARY15 will overwrite the results of the earlier tests then you probably want to search the array from the back to the front.
data want;
set have;
length code $10 ;
array flags primary1-primary15 ;
do index=15 to 1 by -1 ;
if flags[index]='Y' then do;
code=cats('tax-',index);
leave;
end;
end;
run;
@marleeakerson wrote:
Hello,
I am trying to create a macro variable to add a new column. There are 15 primary columns (primary1-primary15) and i want to make a new variable called "Code" that has "tax-" and then the same number as in the primary variable. See example:
if primary1= "Y" then Code=tax1;
if primary2= "Y" then Code=tax2;
if primary3= "Y" then Code=tax3;... up until if primary15="Y" then Code=tax15
Can someone help me please?
See if this gets you started:
data example; set have; array p Primary1-primary15;
length code $ 5; Code= cats('Tax',whichc('Y',of p(*)); run;
The array gives you a handle on a list of variables. The function WHICHC searches a list of variables for the first value given (your Y in this case) in the order listed. The "of p(*)" in effect says to search primary1 then primary2 etc to find Y. It returns the position number of the first match found.
CATS concatenates (combines) character values stripping off any trailing spaces.
If NONE of the values have a Y then Whichc function will return 0 and Tax0 as shown. This can be cleaned up if needed with an If/then statement after creation most likely.
If you expect multiple values of the code because of multiple Y values then you really need to provide an explicit input example set of values and the desired results.
You can use arrays to do this.
data want;
set have;
length code $5.;
array primary(15);
array tax(15);
do i=1 to dim(primary);
if primary(i)="Y" then code=vname(tax(i));
end;
drop i tax:;
run;
April 27 – 30 | Gaylord Texan | Grapevine, Texas
Walk in ready to learn. Walk out ready to deliver. This is the data and AI conference you can't afford to miss.
Register now and lock in 2025 pricing—just $495!
SAS' Charu Shankar shares her PROC SQL expertise by showing you how to master the WHERE clause using real winter weather data.
Find more tutorials on the SAS Users YouTube channel.