DATA Step, Macro, Functions and more

Creating variables within a data step

Posts: 0

Creating variables within a data step

Am trying to create three new indicator variables k_200907, k_200908 and k_200909 into dataset B via macro below, but only created variable k_200909 in the end.

%macro naruto(var1=);

data work.datasetB;
set work.datasetA;
if date < &var1 then k_&var1 = 1;
else if date >= &var1 then k_&var1 = 0;

%mend naruto;

%naruto(var1 = 200907)
%naruto(var1 = 200908)
%naruto(var1 = 200909)

Please could anyone shed some light on why variable k_200907 and k_200908 aren't stored in dataset B? Many thanks. Regards Silverflute
Posts: 8,740

Re: Creating variables within a data step

Simply put, the SAS Macro Facility is like a big, automatic typewriter. Every time you invoke your macro program (%NARUTO), the Macro word scanner and tokenizer is typing the WHOLE DATA step program over again.

So the first invocation creates the resolved code and when the resolved code runs, WORK.DATASETB is created. However, the SECOND invocation again types the DATA step code, with the new values and now THAT resolved code is compiling and executing and is writing OVER the first WORK.DATASETB. And THEN, the same thing happens again the THIRD time you invoke your macro program. So what you're left with is the 3rd version of WORK.DATASETB.

I would recommend that you read up a bit on how SAS Macros work by searching for previous forum postings or using Google to search for SAS Macro tutorials from user groups. Here's a paper to get you started:

If you want to create variable k_200907 and k_200908 and k_200909 in the same dataset, you will have to redesign how your macro program works and how it generates the DATA step program. Here's a hint, a macro program can generate WHOLE steps, such as whole procedure steps or whole DATA step programs or a macro program can generate parts of statements within a procedure or program or can generate multiple statements. Your macro program does NOT have to contain an entire complete DATA step program to accomplish what you want to do. But this also means that your macro invocation might have to change.

Posts: 0

Re: Creating variables within a data step

Many thanks Cynthia
Super Contributor
Posts: 647

Re: Creating variables within a data step

when you pass var1 = 200907 then only k_200907 is created.
the next time k_200907 will be over written by other values that you pass(200908,200909).
so at any given time with your logic only one variable will be created.

try to pass three parameters and var1=, var2=, var3= and add the logic in the code in the if-then else statement.
Posts: 0

Re: Creating variables within a data step

Many thanks SAS Phile
Ask a Question
Discussion stats
  • 4 replies
  • 3 in conversation