BookmarkSubscribeRSS Feed
Ronein
Meteorite | Level 14

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.

sas-innovate-2024.png

Available on demand!

Missed SAS Innovate Las Vegas? Watch all the action for free! View the keynotes, general sessions and 22 breakouts on demand.

 

Register now!

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
  • 4466 views
  • 2 likes
  • 4 in conversation