BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
A_Halps
Obsidian | Level 7

Hi,

I am trying to go from:

SSN   TEST  

1          1       

2          4       

2          2       

3          2       

 

TO:

SSN   TEST   FLAG

1          1         .

2          4         1

2          2         1

3          2         .

 

So, I want to create a flag that if the test=4 then each flag for that specific person will be 1.

 

This is what I currently have, but it is not grouping it by person and is continuing down the entire list, which is not what i want.

 

data want;
set have;
by ssn;
if test=4 then flag=1;
retain flag;
run;

1 ACCEPTED SOLUTION

Accepted Solutions
PeterClemmensen
Tourmaline | Level 20

If you know that test = 4 is the first in each group, a simpler single-pass solution could be

 

data have;
input SSN TEST;
datalines;
1 1 
2 4 
2 2 
3 2 
;

data want;
   set have;
   by ssn;
   if first.ssn then flag = .;
   if test = 4 then flag = 1;
   retain flag;
run;

View solution in original post

5 REPLIES 5
PeterClemmensen
Tourmaline | Level 20

So if TEST = 4 for any obs in a group, then flag = 1 for all obs in that group?

A_Halps
Obsidian | Level 7
Yes. And I currently have it set up with 4 is the top because i sorted it by ssn and descending test (4 is the highest it goes).
PeterClemmensen
Tourmaline | Level 20

If so then do

 

data have;
input SSN TEST;
datalines;
1 1 
2 4 
2 2 
3 2 
;

data want;
   do _N_ = 1 by 1 until (last.ssn);
      set have;
	  by ssn;
	  if test = 4 then flag = 1;
   end;

   do _N_ = 1 to _N_;
      set have;
      output;
   end;
run;
A_Halps
Obsidian | Level 7
What does "_N_ = 1 " do?
PeterClemmensen
Tourmaline | Level 20

If you know that test = 4 is the first in each group, a simpler single-pass solution could be

 

data have;
input SSN TEST;
datalines;
1 1 
2 4 
2 2 
3 2 
;

data want;
   set have;
   by ssn;
   if first.ssn then flag = .;
   if test = 4 then flag = 1;
   retain flag;
run;

SAS Innovate 2025: Save the Date

 SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!

Save the date!

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
  • 5 replies
  • 741 views
  • 1 like
  • 2 in conversation