BookmarkSubscribeRSS Feed
☑ This topic is solved. Need further help from the community? Please sign in and ask a new question.
AmirSari
Quartz | Level 8

Hi everyone,

 

I want to add column Y from table B to table A if, for each ID, the values in column Y are right after or before the values of column X in table A.

 

table A:

ID    X

1     9

2     6

3   11

 

table B:

ID    Y

1     4

1     3

1     7

1     11

1     16

2     1

2     8

2     5

2     9

3   7

3   9

3   14

3   13

 

What I need:

ID    X     Y

1     9     7

1     9    11

2     6     5

2     6     8

3   11     9

3   11     13

 

 

Thank you!

1 ACCEPTED SOLUTION

Accepted Solutions
andreas_lds
Jade | Level 19

Just an idea:

data distance;
   merge two one;
   by Id;
   
   d = x - y;
   s = sign(d);
   d = abs(d);
run;

proc sort data=distance out=sorted;
   by id s d;
run;

data want;
   set sorted;
   by id s;
   
   if first.s;
   
   drop s d;
run;

View solution in original post

3 REPLIES 3
Tom
Super User Tom
Super User

You could probably get away with interleaving the two datasets.

First let's convert your example listings into actual datasets.

data a;
  input id x;
cards;
1  9
2  6
3 11
;
data b;
  input id y ;
cards;
1 4
1 3
1 7
1 11
1 16
2 1
2 8
2 5
2 9
3 7
3 9
3 14
3 13
;

For the interleaving to work they need to be sorted.

proc sort data=a;
  by id x;
run;
proc sort data=b;
  by id y;
run;

Now since you want to interleave by both the ID and the other variable you will have rename on on the way in.

To find the previous value use LAG().

data want;
  set b(in=inb rename=(y=x)) a(in=ina);
  by id x;
  lagx=lag(x);
  if first.id then lagx=.;
  if ina then y=lagx;
  if inb and not first.id and lag(ina)=1 then do; y=x; x=lagx; end;
  if not missing(y);
  drop lagx;
run;
AmirSari
Quartz | Level 8
Thank you! This also worked!
andreas_lds
Jade | Level 19

Just an idea:

data distance;
   merge two one;
   by Id;
   
   d = x - y;
   s = sign(d);
   d = abs(d);
run;

proc sort data=distance out=sorted;
   by id s d;
run;

data want;
   set sorted;
   by id s;
   
   if first.s;
   
   drop s d;
run;

SAS Innovate 2025: Call for Content

Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!

Submit your idea!

How to Concatenate Values

Learn how use the CAT functions in SAS to join values from multiple variables into a single value.

Find more tutorials on the SAS Users YouTube channel.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

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