BookmarkSubscribeRSS Feed
docsaurmi
Calcite | Level 5

Hello, I have 3 excel data sets named data 1,data 2 and data 3 with common variable id. I have imported them using MACRO. I have merged (data 1 ,data 2 and data 3 data 2) in the following way,

 

%macro merge (factor,m,n);

data &factor;

merge %do i = &m %to &n;

data&i

%end;

;

by id;

run;

proc print data = &factor;

run;

%mend merge;

%merge (combine1, 1,2);

%merge (combine2, 2,3);

 

Now, I need to solve this

 

1. merge data 1 and data 2 so that I have records only for those values of ID that are in data 1.

2. merge all three files so that I have records only for those values of ID that are in all 3 datasets.

 

How can I write the SAS MACRO code for these?

6 REPLIES 6
slangan
Obsidian | Level 7

You should use the IN option:

 

https://onlinecourses.science.psu.edu/stat481/node/18

 

docsaurmi
Calcite | Level 5

How can I use 'in' option in MACRO code?

 

Reeza
Super User
Why are you doing this via a macro? It seems like a single/simple data step would work?
docsaurmi
Calcite | Level 5

I am just trying to use MACRO in this case.

Patrick
Opal | Level 21

Below should work.

%macro merge (factor,m,n);

  data &factor;
    merge 
      %do i = &m %to &n;
        data&i (in=in&i)
      %end;
      ;
    by id;

    %do i = &m %to &n;
      if in&i;
    %end;

  run;

  proc print data = &factor;
  run;

%mend merge;

%merge (combine1, 1,2);
%merge (combine2, 2,3);
Astounding
PROC Star

This is actually a good exercise to use, to learn more about writing macros.

 

First, this line in your macro will change:

 

data&i

 

Instead, it will add the IN= variables:

 

data&i (in=in&i)

 

The other piece that changes is a bit more complex.  It will add a statement after the BY statement, to subset observations.  It will genereate something like this:

 

if in1 and in2 and in3;

 

To do that, all of this code goes between the BY statement and the RUN statement:

 

if

%do i=&m to &n;

in&i

%if &i < &n %then and;

%end;

;

 

Try to match up the pieces of the macro version to the pieces of the hard-coded IF statement.

 

Good luck.

hackathon24-white-horiz.png

2025 SAS Hackathon: There is still time!

Good news: We've extended SAS Hackathon registration until Sept. 12, so you still have time to be part of our biggest event yet – our five-year anniversary!

Register Now

How to connect to databases in SAS Viya

Need to connect to databases in SAS Viya? SAS’ David Ghan shows you two methods – via SAS/ACCESS LIBNAME and SAS Data Connector SASLIBS – in this video.

Find more tutorials on the SAS Users YouTube channel.

Discussion stats
  • 6 replies
  • 2145 views
  • 0 likes
  • 5 in conversation