geniusakii
geniusakii

Reputation: 133

Count by variables with criteria in SAS

I have the following dataset. I want to create a Flag(Score>50) column for each student to get the count of subjects with marks greater than 50. I know a way do this by creating a flag using an if condition for each subject and then add them but just curious if there is a better way of doing that in SAS? thanks!!

Student_ID,Physics,Maths,Social,English,Chemistry,Flag(Score>50)
1011,90,90,60,30,20,3
1012,60,90,30,40,40,2
1013,30,10,80,70,50,2
1014,70,10,40,90,90,3

data score1;
set score;
if Physics > 50 then Phy_flag = 1;
if Maths > 50 then Math_flag=1;
if Social > 50 then Social_flag=1;
if English > 50 then Eng_flag=1;
if Chemistry > 50 then Chem_flag=1;
Flag_Score_50 = sum(Phy_flag,Math_flag,Social_flag,Eng_flag,Chem_flag);
run;

This is what I have done but I have too many variables in other dataset and I don't want to write these if conditions so many times. tx

Upvotes: 1

Views: 141

Answers (2)

Shenglin Chen
Shenglin Chen

Reputation: 4554

Directly use sum:

data have;
infile cards dlm=',';
input Student_ID Physics Maths Social English Chemistry;
flag=sum(Physics > 50,Maths > 50, Social > 50,English > 50,Chemistry > 50);
cards;
1011,90,90,60,30,20
1012,60,90,30,40,40
1013,30,10,80,70,50
1014,70,10,40,90,90
;
proc print;
run;

Upvotes: 0

DomPazz
DomPazz

Reputation: 12465

Use an array to hold the scores of the different subjects then just loop over the array, counting the values > 50.

data score1;
set score;
array subj[5] Physics Maths Social English Chemistry;

Flag_Score_50 = 0;
do i=1 to 5;
   if subj[i] > 50 then
      Flag_Score_50 = Flag_Score_50 + 1;
end;
drop i;
run;

Upvotes: 1

Related Questions