Programming the statistical procedures from SAS

Combining multiple datasets using a loop

Accepted Solution Solved
Reply
Frequent Contributor
Posts: 117
Accepted Solution

Combining multiple datasets using a loop

Hi

A quick question.

I have several datasets (HR1, HR2, HR3,.....HR 20)

I need to combine a number of these tables using (data..set) according to certain criteria, since this is a repetitive task I chose to build a macro like this

%macro repeat_set(n=);

%do var=1 %to &n;

Data j;

if &var=1 then do;

           set HR&var;

           end;

else if &var gt 1 then do;

           set j HR&var;

    end;

run;

%end;

%mend;

The reason why I am doing this is that the new dataset 'J' dose not exist from the beginning, so while looping, the idea is when the code takes the first HR set (HR1) it will create 'j' using the following:

data j;

set HR1;

run;

and for the consequent sets, like HR2 , it will do

data j;

set j HR2;

run;

and so on

So when I do a

%repeat_set(n=1);


the code executes correctly


BUT, when I do anything larger than 1, ex

%repeat_set(n=5);


The code combines only tables HR2-HR5. It seems as if HR1 contribution to the new set 'j' is "deleted" during the process.

Any suggestions?

Best regards



Accepted Solutions
Solution
‎06-25-2015 09:27 PM
Frequent Contributor
Posts: 117

Re: Combining multiple datasets using a loop

The reason is that it is a part of a larger code that I need to actively decide the number of tables to include, and I need to programatically be able to change one value in the code rather than changing it at several places

Anyhow, found the problem myself (missing %), but your code works too of course

Kind regards

View solution in original post


All Replies
Super User
Super User
Posts: 6,137

Re: Combining multiple datasets using a loop

Why not just combine them all in one step?

data want ;

  set hr1-hr20;

run;

Solution
‎06-25-2015 09:27 PM
Frequent Contributor
Posts: 117

Re: Combining multiple datasets using a loop

The reason is that it is a part of a larger code that I need to actively decide the number of tables to include, and I need to programatically be able to change one value in the code rather than changing it at several places

Anyhow, found the problem myself (missing %), but your code works too of course

Kind regards

Super User
Super User
Posts: 6,137

Re: Combining multiple datasets using a loop

How are you "actively" deciding how many tables to include?  Do you mean the parameter N to the macro?

%let n=5 ;

data J;

  set hr1-hr&n;

run;

☑ This topic is SOLVED.

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

Discussion stats
  • 3 replies
  • 265 views
  • 6 likes
  • 2 in conversation