DATA Step, Macro, Functions and more

Merge or join

Accepted Solution Solved
Reply
Contributor
Posts: 29
Accepted Solution

Merge or join

Hi I need to merge two datasets but not sure if I can do it with data step.

My datasets look like this;

 

Dataset 1            Dataset 2

ID     Var1          ID      var2

1          a             2          a

2         b              5          b

3          c             3           c

4         d              4          d

 

When I merge these two datasets, I only want to keep all IDs from dataset 1 and add from dataset 2 if IDs match.

So I want a final dataset to look like this;

 

Data_merged

ID   var1  var2

1       a

2       b       a

3       c       c

4      d        d

 

Thanks much!

 


Accepted Solutions
Solution
‎11-23-2017 03:38 PM
PROC Star
Posts: 1,400

Re: Merge or join

Yes. Except you don't need your in=b in this case and you have to make sure that the two data sets are properly sorted.

View solution in original post


All Replies
PROC Star
Posts: 1,400

Re: Merge or join

[ Edited ]

Like this?

 

data Dataset_1;
input ID$ Var1$;
datalines;
1 a
2 b
3 c
4 d
;

data Dataset_2;
input ID$ var2$;
datalines;
2 a
5 b
3 c
4 d
;

/* Data Step Approach */
proc sort data=Dataset_1; by ID; run;
proc sort data=Dataset_2; by ID; run;

data merged;
	merge Dataset_1(in=a) Dataset_2;
	by ID;
	if a;
run;

/* Proc SQL Approach */
proc sql;
	create table joined as
	select * 
	from Dataset_1 left join Dataset_2
	on Dataset_1.ID = Dataset_2.ID ;
quit;
Contributor
Posts: 29

Re: Merge or join

Hi,

I tried

data want;

merge data1 (in=a) data2 (in=b);

by id;

if a;

run;

 

This is the same as what you suggested?

 

Thanks

Solution
‎11-23-2017 03:38 PM
PROC Star
Posts: 1,400

Re: Merge or join

Yes. Except you don't need your in=b in this case and you have to make sure that the two data sets are properly sorted.

☑ This topic is solved.

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

Discussion stats
  • 3 replies
  • 178 views
  • 2 likes
  • 2 in conversation