Home > Back-end >  How to use arrays in sas?
How to use arrays in sas?

Time:10-23

enter image description here

How to perform calculation using arrays in SAS?

source file scholar
Anne C A C D B E D D B A
Vicky C C C E B E D B A 
Laurel D D C D B E D D B A
Victor C A C D B E D D A D
Dimple C A C D B E D D B A
Godfrey B D C B D D D B B A
Denny C D C B E E D B B A
Richard C A C D B E D D B A

CodePudding user response:

Try this

data have;
input name $ (q1 - q10)(:$1.);
infile datalines missover;
datalines;
Anne    C A C D B E D D B A 
Vicky   C C C E B E D B A 
Laurel  D D C D B E D D B A 
Victor  C A C D B E D D A D 
Dimple  C A C D B E D D B A 
Godfrey B D C B D D D B B A 
Denny   C D C B E E D B B A 
Richard C A C D B E D D B A
;

data want;
   set have;
   array a {10} $ _temporary_ ("C", "A", "C", "D", "B", "E", "D", "D", "B", "A");
   array q q1 - q10;
   total = 0;
   
   do over q;
      if q = a[_I_] then total   1;
   end;
   
   Result = ifc(total ge 7, "Passed", "Failed");
run;

Result:

Obs name    q1  ------------q10  total Result
1   Anne    C A C D B E D D B A  10    Passed
2   Vicky   C C C E B E D B A    5     Failed
3   Laurel  D D C D B E D D B A  8     Passed
4   Victor  C A C D B E D D A D  8     Passed
5   Dimple  C A C D B E D D B A  10    Passed
6   Godfrey B D C B D D D B B A  4     Failed
7   Denny   C D C B E E D B B A  6     Failed
8   Richard C A C D B E D D B A  10    Passed

CodePudding user response:

Not sure why, but there u go

data want;
   set have;
   array a {10} $ _temporary_ ("C", "A", "C", "D", "B", "E", "D", "D", "B", "A");
   array t {10}   _temporary_ (10 * 0);
   array q q1 - q10;
   
   do over q;
      if q = a[_I_] then t[_I_] = 1;
   end;
   
   total = sum(of t[*]);
   Result = ifc(total ge 7, "Passed", "Failed");
   
   call stdize('replace', 'mult=', 0, of t[*], _N_);
run;

CodePudding user response:

I suspect you want to use simpler constructs like below:

data want;
   set have;
   array a {10} $ _temporary_ ("C", "A", "C", "D", "B", "E", "D", "D", "B", "A");
   array correct_answer(10) correct_answer1-correct_answer10 ;
   array q q1 - q10;

   
   do i=1 to dim(a);
      if q = a[_I_] then correct_answer = 1;
      else correct_answer=0;
   end;

   Total = sum(of correct_answer1-correct_answer10);

   if total>= 7 then result="Passed"; 
   else result ="Failed"; 
run;

  • Related