11-14-2016 02:23 PM - last edited on 11-14-2016 03:32 PM by Reeza
This is my first time posting, so I'm sorry if this is in the wrong location! I am new to the macro language and am trying to write one of my first macros. I'm trying to use a do loop to loop through variables with a number contained in them (for example variable1, variable2, variable3, etc.), however, there is one variable that has a number in the middle of it (ex varia#ble). I am able to loop through all of the variables when they end with a number, but the code gets stopped by the varible with the number in the middle.
My current code writes the variable with a number in the middle as varia&i.ble and it's read as two separate variables: varia1 and ble. Is there a way to write code so that it reads variab#ble as one complete variable?
See below for an outline of my code:
%macro ref(var); data test2; set dataset; %do i=1 %to 5; if apple=1 and orange&i ne . and banana&i in (4,.) then grape=2; if apple=1 and orange&i ne . and banana&i in (1,2,3) then grape=1; if grape=' ' and apple=1 and orange&i ne . and pe&iar then grape=2; %end; %mend ref; %ref(1); %ref(2); %ref(3); %ref(4); %ref(5);
11-14-2016 03:33 PM
I corrected one mistake in code by accident in your post
ref(3) was missing a bracket.
You should add a period after the macro variable.
if grape=' ' and apple=1 and orange&i ne . and pe&i.ar then grape=2;
11-14-2016 03:34 PM - edited 11-14-2016 03:38 PM
The code you posted doesn't match what you said in your question. In particular you are missing the period that let's the macro processor know that you have ended the macro variable reference.
In particular this
is referencing a macro variable named IAR. If you want it to reference the macro variable named I then add the period.
So that it can see were the macro variable name ends on the rest of the code begins. You might still have trouble in some situations (especially PROC SQL) so that it might help to add %UNQUOTE() so that parser knows to treat the result as one token.
There are a number of other things strange about your macro defintion. Your DATA step is missing a RUN statement. Your macro defines the parameter VAR but never uses it anywhere. You treat GRAPE as both a numeric and character variable. You keep reassigning values to GRAPE. The last one that runs will win and any previous assignments will get over written.
%macro ref(var); data test2; set dataset; %do i=1 %to 5; if apple=1 and orange&i ne . and banana&i in (4,.) then grape=2; if apple=1 and orange&i ne . and banana&i in (1,2,3) then grape=1; if grape=' ' and apple=1 and orange&i ne . and pe&i.ar then grape=2; %end; run; %mend ref; %ref(1); %ref(2); %ref(3); %ref(4); %ref(5);
11-14-2016 03:41 PM
Your data set won't have the previous history.
You create a test2 dataset each time from a base dataset, so each one is different. Not sure if that makes sense, it will over write the results each time.