BookmarkSubscribeRSS Feed
Ronein
Onyx | Level 15

Hello

For each customer there are multiple rows.

I want to add a new field (binary variable that get value 1 or 0)

IF the value of X in  last row of customer  is equal or greater than 1  then newField=1;

else  newField=0;

Expected values in Newfield for customer 1 are:

1

1

1

1

1

Expected values in Newfield for customer 2 are:

0

0

0

0

0

Why the code below is not giving the wanted result?

 

data c1;
input ID x;
cards;
1 0
1 0
1 1
1 2
1 3
2 0 
2 0 
2 0 
2 0 
2 0 
;
run;


data c2;
set c1;
IF last.ID and x>=1 then Newfield=1;else Newfield=0;
run;
3 REPLIES 3
RW9
Diamond | Level 26 RW9
Diamond | Level 26

What is the sorting variables for that data.  The simplest method to get what you want is to reverse sort the data - so the last record per id is first, then retain that down the data, e.g.:

data want;
  set have;
  retain x;
  if first.id then new_x=ifn(x>1,1,0);
run;

Then sort back to what it is.

If you can't sort your data - and if you cant then your data is not good for working with - then you will need to merge the result back on, something like:

data inter;
  set have;
  by id;
  if last.id then output;
run;

data want (drop=base);
  merge have inter (rename=(x=base));
  by id;
  x=ifn(x>1,1,0);
run;
Ksharp
Super User
data c1;
input ID x;
cards;
1 0
1 0
1 1
1 2
1 3
2 0 
2 0 
2 0 
2 0 
2 0 
;
run;

data want;

do until(last.id);
 set c1;
 by id;
end;
if x>=1 then Newfield=1;else Newfield=0;
do until(last.id);
 set c1;
 by id;
 output;
end;
run;
Astounding
PROC Star

Your code is very close to working.  It is missing the BY statement in the DATA step.  The BY statement is what creates first.ID and last.ID:

 

data c2;
set c1;
by id; IF last.ID and x>=1 then Newfield=1;else Newfield=0; run;

 

Of course, the data must be in order to permit the BY statement.  In your sample data, that is not a problem.  But sometimes you need to run PROC SORT first.

hackathon24-white-horiz.png

The 2025 SAS Hackathon has begun!

It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.

Latest Updates

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 3 replies
  • 5152 views
  • 2 likes
  • 4 in conversation