09-28-2017 11:59 AM
I have 2 datasets:
INPUT VAR1 VAR2 $;
INPUT VAR1 VAR2 $;
I need this result (one-to-many merge):
Im doing this with this proc:
SELECT DATASET1.VAR1, DATASET1.VAR2, DATASET2.VAR2 AS VAR3
FROM DATASET1 INNER JOIN DATASET2 ON DATASET1.VAR1 = DATASET2.VAR1;
But I want to know the most easy way to do it with SAScode, with DATA STEP
How can I do it?
09-28-2017 12:09 PM
This is a many-to-many join, not a one-to-many. Creating a cartesian join in a data step is at least complicated. Stay with SQL.
09-28-2017 12:28 PM
I agree with @KurtBremser, there is no simple DATA step method for this. It is possible you would consider this SQL variation slightly simpler. You could change the second line of the SELECT statement, making it:
FROM DATASET1, DATASET2 where DATASET1.VAR1 = DATASET2.VAR1;
Note that PROC SQL ends with a QUIT; statement, not a RUN; statement.
09-28-2017 01:11 PM - edited 09-28-2017 01:17 PM
Getting a data step to do a many-to-many join with ID variables can be a pain.
Here is an example doing an INNER JOIN (requires that ID is in both input tables) using POINT= option on SET statements to re-read the data. You could also build up hashes if your BY groups are small enough that you can load all of the records into memory.
data want ; * count records per id per table ; * Keep track of first/last record number ; first1=c1+1; first2=c2+1; do until(last.id); set one(in=in1 keep=id) two(in=in2 keep=id); by id; if in1 then do; any1 = 1; c1+1; end; if in2 then do; any2 = 1; c2+1; end; end; * INNER JOIN requires ID to be in both tables ; if (c1>=first1) and (c2>=first2) then do; do p1=first1 to c1 ; set one point=p1 ; do p2=first2 to c2; set two point=p2; output; end; end; end; * drop variables used for tracking ; drop first1 first2 c1 c2 ; run;
09-28-2017 01:37 PM
SQL is definitely easier than DATA step for this task.
But if you are confident that dataset 2 always has exactly 3 observations for each value of the matching var (var1 in your example), you can make a relatively simple data step, using the POINT= option is a SET DATASET2 statment:
data want (drop=_:); set dataset1; by var1; _group+first.var1; do p= 3*_group-2 to 3*_group; set dataset2 (rename=(var2=var3)) point=p; output; end; run;
Now think about the complexities neither dataset has a fixed number of observations per record. You may not want to go there.