DATA Step, Macro, Functions and more

help with if then statement

Reply
Occasional Contributor
Posts: 8

help with if then statement

hi community,

need some help with this problem and how to solve it,

create a new variable lettergrade that reports an a if the GPA is 3.5 or higher, a B is the GPA is greater than equal to 2.5 but less than 3.5, a C iuf GPA us greater than or equal to 1.5 but less than 2.5, a D if it is greater than or equal 0.5 but less than 1.5 and an F if the GPA is below 0.5.

 how can i code this as i have tried several options here

data exam.studentsnew;
set exam.students
/* working from here on finish the variable list from studentsnew*/
keep AveGPA ID sex $ GPA
if GPA > 3.5 then Lettergrade="A";
*else if GPA>=2.5 and GPA<3.5 then Lettergrade="B";
*else if GPA>=1.5 and if GPA<2.5 then Lettergrade="C";
*else if GPA>=0.5 and if GPA<1.5 then Lettergrade="D";
*else Lettergrade = "F";
run;

this does not work and i am stuck. please help.

PROC Star
Posts: 7,360

Re: help with if then statement

Should work (but not quite according to your description) with your current code if you don't comment out the else statements AND include the new variable in your keep statement. However, it could be simplified to just:

if GPA GE 3.5 then Lettergrade="A";
else if GPA GE 2.5 then Lettergrade="B";
else if GPA GE 1.5 then Lettergrade="C";
else if GPA GE 0.5 then Lettergrade="D";
else Lettergrade = "F";

Additionally, if you have any missing GPAs you may want to wrap the above in something like:

if not missing(GPA) then do;

etc., etc.

end;

 

Art, CEO, AnalystFinder.com

Occasional Contributor
Posts: 8

Re: help with if then statement

Thanks so much it worked. appreciate your help.

Super User
Posts: 10,484

Re: help with if then statement

Another approach for value look ups like this is a custom format. If you use this a lot then having a library of formats available can reduce code:

proc format library=work;
value gpa
0.5 -<1.5 = 'D'
1.5 -<2.5 = 'C'
2.5 -<3.5 = 'B'
3.5 - high= 'A'
other = 'F';
run;

data have;
   do gpa = 0 to 4 by .2;
      lettergrade= put(gpa,GPA.);
      output;
   end;
run;

If that format was in a permanent library that was in the format search path then I would not have to recreate the format and can use it in many places. And it does not require adding a variable as most SAS procedures will honor the format for grouping and/or displaypurposes in analysis procedures:

 

proc freq data=have;
   tables gpa;
   format gpa gpa.;
run;

Note that the code above used the raw variable and not a created text variable.

 

Occasional Contributor
Posts: 8

Re: help with if then statement

thank you so much, it works

Ask a Question
Discussion stats
  • 4 replies
  • 119 views
  • 0 likes
  • 3 in conversation