Using If....Else in SAS!!!



                       Two of the basic tools for conditional processing are the IF and ELSE IF statements. To understand how these statements work, we will look some examples based on these statements.

     Dataset:

    *creating a new datset called school;

      data A15028.A28_school;

      input Age Quiz $ Midterm Final;
      datalines;
      12 A 92 95
      12 B 88 88
      13 C 78 75
      13 A 92 93
      12 F 55 62
      13 B 88 82
       ;

## Problem Statement:

                      Using IF and ELSE IF statements, we have to compute two new variables for the following data set:  

        1)    Grade (numeric), with a value of 6 if Age is 12 and a value of 8 if Age is 13

       2)     Using this information, compute a course grade (Course) as a weighted average of the Quiz (20%), Midterm (30%) and Final (50%).

## Solution:

                      It is good practice a create a permanent library and save the work in the that. The permanent library ends when the session ends. So next time if you want to execute the programm you should call the permanent library again.

libname A15028 "/folders/myfolders";

                     Libname is the SAS keywork to create a permanent SAS library. I will use A15028 as mu library name throughout my posts. But you can create your own library name. Then the path for the library.


data A15028.A28_school1;

*subsetting the school datast;

set A15028.A28_school;
*Assiginig the grades based on the age;
if age = 12 then grade =6;
else if age eq 13 then grade=8;
*Replacing the quiz value based on the type;
if Quiz eq "A" then quiz=95;
if Quiz eq "B" then quiz=85;
if Quiz eq "C" then quiz=75;
if Quiz eq "F" then quiz=65;
*Calculating the coursegrade based on the weightage for different exams;
coursegrade = 0.2*Quiz+0.3*Midterm+0.5*Final;
run;
PROC PRINT DATA=A15028.A28_school1;
RUN;


                    The above program creates a two new variables called grade and course grade based on the given conditions. Also you can see comments in between the program which will explain each line. In SAS comment can be made by two methods like (*.....;) or (/*....*/).

##Output:



                   Thus, if you see the output two new variables are created and we are segregated the grade and course grade by the given conditions. We are creating two new variables based on the IF else conditions by using logical operators.


                   Yes, there are lot of ways to reduced the size of the program and since my aim to make the program clear and understandable, I will initially use a explanatory kind of program. In future we can see how to write the same program in efficient manner.

No comments:

Post a Comment