How to make a variable to be '1' if it is the first instance of a new variable in a by group?

Accepted Solution Solved
Reply
N/A
Posts: 1
Accepted Solution

How to make a variable to be '1' if it is the first instance of a new variable in a by group?

See the title and the attached file. How do I write the SAS code to create variable 3? I am not very experienced with SAS, so any help would be greatly appreciated. Thank you!

Edit- Thank you Bruno, that worked perfectly!


Accepted Solutions
Solution
‎03-22-2014 06:07 PM
SAS Super FREQ
Posts: 709

Re: How to make a variable to be '1' if it is the first instance of a new variable in a by group?

Hi

Assuming the input data is sorted by var_1, then the following code should do what you want:

data want;
  set have;
  by Var_1;
  if first.var_1 = 1 then do;
   
retain checkForA;
    checkForA = 1;
 
end;
 
if checkForA = 1 and var_2 = "A" then do;
    var_3_sas =
1;
    checkForA =
0;
 
end;
  var_3_sas = coalesce(var_3_sas,
0);
run;

View solution in original post


All Replies
Solution
‎03-22-2014 06:07 PM
SAS Super FREQ
Posts: 709

Re: How to make a variable to be '1' if it is the first instance of a new variable in a by group?

Hi

Assuming the input data is sorted by var_1, then the following code should do what you want:

data want;
  set have;
  by Var_1;
  if first.var_1 = 1 then do;
   
retain checkForA;
    checkForA = 1;
 
end;
 
if checkForA = 1 and var_2 = "A" then do;
    var_3_sas =
1;
    checkForA =
0;
 
end;
  var_3_sas = coalesce(var_3_sas,
0);
run;
🔒 This topic is solved and locked.

Need further help from the community? Please ask a new question.

Discussion stats
  • 1 reply
  • 199 views
  • 0 likes
  • 2 in conversation