This macro code creates the code below. I want to create only one length statement and only variable names changing dynamically.
data test; input var1 $ var2 $; cards; 1 4 2 5 3 6 ; %macro m; data test; %do i= 1 %to 2; length var&i $ 10.; %end; set test; run; %mend m; %m /* cod generated */ data test; length var1 $ 10.; length var2 $ 10.; set test; run; /* desired code */ data test; length var1 $ 10. var2 $ 10.; set test; run;
Definitely a worthwhile technique to learn!
Here's what you have now:
%do i=1 %to 2;
length var&i $ 10.;
%end;
Here's what the replacement would look like (notice the dot is not required when defining length, only for formats):
length
%do i=1 %to 2;
var&i
%end;
$ 10;
Good luck.
Definitely a worthwhile technique to learn!
Here's what you have now:
%do i=1 %to 2;
length var&i $ 10.;
%end;
Here's what the replacement would look like (notice the dot is not required when defining length, only for formats):
length
%do i=1 %to 2;
var&i
%end;
$ 10;
Good luck.
@data_null__ @Astounding. Thank you. May be I could start another thread. What if variables are not var1 and var2 (ie. can not referenced by macro variable &i) such as x and y and I need to change their attributes inside macro definition.
data test;
input x $ y $;
cards;
1 4
2 5
3 6
;
The answer depends on how the variable names are stored. For example, do you have a macro variable holding a list of variable names:
%let var_list = x var1 y;
Do you have a data set where a DATA step variable takes on values of "x" "var1" and "y"?
How do you expect to provide the list of variable names?
When you already have all the variable names assembled in a single macro variable, I would skip the looping:
length &var_list $ 10;
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.