Help using Base SAS procedures

macro do loop problem

Accepted Solution Solved
Reply
Contributor
Posts: 38
Accepted Solution

macro do loop problem

I want to repeat each country's obs. for 31 times and the following statements run well.

%let country1=abudhabi;

%let country2=argentina;

%macro x;

data  %do i =1 %to 31;

                work.&country1&i

         %end;;

set    &country1;

run;

data  %do i =1 %to 31;

                work.&country2&i

         %end;;

set    &country2;

run;

%mend x;

%x;

But because I have tens of countries, I also want to apply the do loop on "countryj". The commands I want is something like the commands below but it failed. Can anyone give me some advice? Thanks.

%let country1=abudhabi;

%let country2=argentina;

%macro x;

%do j = 1 %to 2;

data  %do i =1 %to 31;

                work.&&country&j&i

         %end;;

set    &&country&j;

run;

%end;

%mend x;

%x;


Accepted Solutions
Solution
‎06-14-2012 10:10 AM
Super User
Posts: 5,069

Re: macro do loop problem

Examine how the extra ampersand plays out.

&&country&i&j

The fist time through the loops, this becomes

&country11

And there is no such macro variable.  You would need to take advantage of using a dot to end a macro variable name, changing this to:

&&country&i..&j

On a secondary note, it might be easier to read the names if you change them slightly:

&&country&i.._&j

Good luck.

View solution in original post


All Replies
Solution
‎06-14-2012 10:10 AM
Super User
Posts: 5,069

Re: macro do loop problem

Examine how the extra ampersand plays out.

&&country&i&j

The fist time through the loops, this becomes

&country11

And there is no such macro variable.  You would need to take advantage of using a dot to end a macro variable name, changing this to:

&&country&i..&j

On a secondary note, it might be easier to read the names if you change them slightly:

&&country&i.._&j

Good luck.

Occasional Contributor
Posts: 8

Re: macro do loop problem

Looks like you all set, but here is another solution:

/* If you already have a data set with all the country names then you don't need this data step */
/* Just use your countries data set in the proc sql step. */
/* Otherwise, create a data set with all of your countries */
data countries;
country='argentina';output;
country='abudhabi';output;
run;

proc sql noprint;
select count(*)
   into :countries
   from countries
;
quit;

%macro x;

%do i=1 %to &countries.;

proc sql noprint;
  select country
    into :country
    from countries (firstobs=&i. obs=&i.)
  ;
quit;

%let country=%trim(%left(&country.));

/* You probably won't need this data step, I did just to make the code work */
data &country.;
  country="&country.";
run;

data
  %do j=1 %to 31;
  work.&country.&j.
  %end;
;
  set &country.;
run;

%end;

%mend x;

%x;

☑ This topic is SOLVED.

Need further help from the community? Please ask a new question.

Discussion stats
  • 2 replies
  • 243 views
  • 1 like
  • 3 in conversation