Hello
For each customer ID there is information of score in 6 months.
I want to check for each customer if he/she touch score 11 (Score 11 meaning is failure).
This code is working perfect.
However ,I want to understand how it works.
As I see the new variable "Flag_Failure" remember the value that was before (IF it was 11 ).
May anyone explain please?
Data a;
input ID Score1 Score2 Score3 Score4 Score5 Score6;
cards;
1 2 2 2 2 2 3
2 8 8 11 11 11 10
3 7 6 7 7 8 8
4 11 11 11 11 10 10
;
run;
Data b;
set a;
Flag_Failure=0;
array diag{6} Score1-Score6;
do i=1 to 6;
if diag{i} in (11)then Flag_Failure=1;
end;
Drop i;
Run;
Think of it this way: If the i'th element of the array is 11 then Flag_Failure=1. Else do not touch Flag_Failure. That means that Flag_Failure will be 1 if just one of the elements is equal to 11. SAS does not reinitialize the variable within the loop. You do that yourself before the loop with Flag_Failure=0. I added a few Put Statements to your code below, hopefully it will make more sense.
Data b;
set a;
Flag_Failure=0;
array diag{6} Score1-Score6;
put "Before Loop: " Flag_Failure=;
do i=1 to 6;
if diag{i} in (11) then Flag_Failure=1;
put "Inside Loop: " (diag[i])(=)Flag_Failure=;
end;
put "After Loop: " Flag_Failure= //;
Drop i;
Run;
You are correct. The indicator variable i runs through the array and sets Flag_Failure to 1 if it encounters a 11 value. Simple as that. You may consider using the Whichn Function for a job like this though..
data b;
set a;
Flag_Failure = whichn(11, of score:) > 0;
run;
I just don't understand how the code is working.
Let's look for example at ID 2 that have scores
8 8 11 11 11 10
diag{1} is 8 so Flag_Failure=0
then diag{2} is 8 so Flag_Failure=0
then diag{3} is 11 so Flag_Failure=1
then diag{4} is 11 so Flag_Failure=1
then diag{5} is 11 so Flag_Failure=1
then diag{6} is 11 so Flag_Failure=0
So why finally we get Flag_Failure=1???
Think of it this way: If the i'th element of the array is 11 then Flag_Failure=1. Else do not touch Flag_Failure. That means that Flag_Failure will be 1 if just one of the elements is equal to 11. SAS does not reinitialize the variable within the loop. You do that yourself before the loop with Flag_Failure=0. I added a few Put Statements to your code below, hopefully it will make more sense.
Data b;
set a;
Flag_Failure=0;
array diag{6} Score1-Score6;
put "Before Loop: " Flag_Failure=;
do i=1 to 6;
if diag{i} in (11) then Flag_Failure=1;
put "Inside Loop: " (diag[i])(=)Flag_Failure=;
end;
put "After Loop: " Flag_Failure= //;
Drop i;
Run;
Good news: We've extended SAS Hackathon registration until Sept. 12, so you still have time to be part of our biggest event yet – our five-year anniversary!
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.
Ready to level-up your skills? Choose your own adventure.