Saturday, 3 October 2015

Welcome to SAS 

Part 2

1. Proc Reports
Although you can customize the output produced by PROC PRINT, there are times when
you need a bit more control over the appearance of your report. PROC REPORT was developed to fit this need. Not only can you control the appearance of every column of your report, you can produce summary reports as well as detail listings.
Two very useful features of PROC REPORT, multiple-panel reports and text wrapping within a column. We will look more about Proc Report by the following example.

#Problem:
Using the SAS data set Blood Pressure we have to create a new variable called Hypertensive which is mentioned as Yes for females (Gender=F) if the SBP is greater than 138 or the DBP is greater than 88 and No otherwise. For males (Gender=M), Hypertensive is defined as Yes if the SBP is over 140 or the DBP is over 90 and No otherwise.

#Data set:

*Creating Bloodpressure dataset;
data A15011.A11_bloodpressure;
   input Gender : $1. 
         Age
         SBP
         DBP;
datalines;
M 23 144 90
F 68 110 62
M 55 130 80
F 28 120 70
M 35 142 82
M 45 150 96
F 48 138 88
F 78 132 76
;

#Solution:

title "Hypertensice Patients";
proc report data=A15011.A11_bloodpressure nowd;
column Gender SBP DBP Hypertensive;
define Gender / Group width=6;
define SBP / display width=5;
define DBP / display width=5;
define Hypertensive / computed "Hypertensive?" width=13;
compute Hypertensive / character length=3;
if Gender = 'F' and (SBP gt 138 or DBP gt 88)
then Hypertensive = 'Yes';
else Hypertensive='No';
if Gender = 'M' and
(SBP gt 140 or DBP gt 90)
then Hypertensive = 'Yes';
else Hypertensive = 'No';
endcomp;
run;
quit;

#Output:


#Explanation:

In the above program we are trying to check whether the person is Hypertensive or not.  For that we need an output based on the requirements which is explained in the problem statement. In the solution we use a statement called DEFINE which is used to specify the usage for each variable. Learning how to control whether to produce a detail listing or a summary report and what
statistics to produce leads you to the DEFINE statement. The DEFINE option DISPLAY is an instruction to produce a detailed listing of all observations. Besides defining the usage as DISPLAY, the DEFINE statement also carry a GROUP option when we need to club the data.

Another import thing in the above program is COMPUTE. One powerful feature of PROC REPORT is its ability to compute new variables. This makes PROC REPORT somewhat unique among SAS procedures. We can use the compute statements to create a COMPUTE block where we can define the new variables inside the block. Here we compute whether he patient is Hypertensive or not based on the SBP and DB values using the IF else statements which we already learned. Also, we used quit statement to stop the procedure, otherwise it wont stop.

2. Proc Means

In this post, we will see about PROC Means which is more versatile and can be used to create summary data sets that can then be analyzed with more DATA or PROC steps.By default, PROC MEANS produces statistics on all the numeric variables in the input SAS data set. Let's see some examples.


#Problem:

Using the SAS data set College, report the mean GPA for the following categories of
ClassRank: 0–50 = bottom half, 51–74 = 3rd quartile, and 75 to 100 = top quarter.

#Dataset:

*Creating user defined format;
proc format library=A15011;
   value $yesno 'Y','1' = 'Yes'
                'N','0' = 'No'
                ' '     = 'Not Given';
   value $size 'S' = 'Small'
               'M' = 'Medium'
               'L' = 'Large'
                ' ' = 'Missing';
   value $gender 'F' = 'Female'
                 'M' = 'Male'
                 ' ' = 'Not Given';
run;
*Calling the format library;
option FMTSEARCH=(A15011);
*Creating college dataset;
data A15011.A11_college;
   length StudentID $ 5 Gender SchoolSize $ 1;
   do i = 1 to 100;
      StudentID = put(round(ranuni(123456)*10000),z5.);
      if ranuni(0) lt .4 then Gender = 'M';
      else Gender = 'F';
      if ranuni(0) lt .3 then SchoolSize = 'S';
      else if ranuni(0) lt .7 then SchoolSize = 'M';
      else SchoolSize = 'L';
      if ranuni(0) lt .2 then Scholarship = 'Y';
      else Scholarship = 'N';
      GPA = round(rannor(0)*.5 + 3.5,.01);
      if GPA gt 4 then GPA = 4;
      ClassRank = int(ranuni(0)*60 + 41);
      if ranuni(0) lt .1 then call missing(ClassRank);
      if ranuni(0) lt .05 then call missing(SchoolSize);
      if ranuni(0) lt .05 then call missing(GPA);
      output;
   end;
   format Gender $gender1. 
          SchoolSize $size. 
          Scholarship $yesno.;
   drop i;
run;

#Solution:

proc format;
value rank 0-50 = 'Bottom Half'
51-74 = 'Third Quartile'
75-100 = 'Top Quarter';
run;
title "Statistics on the College Data Set";
title2 "Broken down by School Size";
proc means data=A15011.A11_college
n
mean
maxdec=2;
class ClassRank;
var GPA;
format ClassRank rank.;
run;

#Output:



#Explanation:


In the above program we tried to do some basic statistical calculation Mean which is to be said as average in the common man term. The data set which we used is College which we are seeing for most of the posts and that is not our interest of this post. So, we will concentrate on the solution part. The Proc Means procedure helps us to calculate the average of the variable. Here we are calculating the average of GPA based on the Class Rank where we created a range for the rank using Proc Format procedure. The options "n" gives the Number of persons and "Mean" gives the average value for that particular section of students and we can adjust the value as 2 decimal point by giving "Maxdec" option.

PROC MEANS lets you use a CLASS statement in place of a BY statement. The CLASS statement performs a similar function to the BY statement, with some significant differences. If you are using PROC MEANS to print a report and are not creating a summary output data set, the differences in the printed output between a BY and CLASS statement are basically cosmetic. The main difference, from a programmer’s perspective, is that you do not have to sort your data set before using a CLASS statement. Similarly, You can control which variables to include in the report by supplying a VAR statement.

3. PROC Tabulate


PROC TABULATE is an underused, under appreciated procedure that can create a wide
variety of tabular reports, displaying frequencies, percentages, and descriptive statistics such as sums and means) broken down by one or more CLASS variables. There are several excellent books devoted to PROC TABULATE. This posts introduces you to this procedure and, we hope, piques your interest.

#Problem:
Using the college data set which was given in my previous post, we should tabulate using the Proc Tabulate procedure.

#Solution:

title "Demographics from COLLEGE Data Set";
proc tabulate data=A15011.A11_college format=6.;
class Gender Scholarship SchoolSize;
tables SchoolSize all,
Gender Scholarship all/ rts=15;
keylabel n=' '
all = 'Total';
run;

#Output::


#Explanation:

PROC TABULATE uses a CLASS statement to allow you to specify variables that
represent categories (often character variables) where you want to compute frequencies
or percentages. So here we want to broke down the data based on the school size and type and Gender as well. Next, the TABLE statement specifies the table’s appearance. Any variable listed in a TABLE statement must be listed in a CLASS statement.

Apart from the above two keywords, we used format option which helps to display in the specific format for every cell in the table. Unlike many other SAS procedures, there are some reserved keywords used by PROC TABULATE and one such keyword is ALL. When you place ALL after a variable name in a table request, PROC TABULATE includes a column representing all levels of the preceding variable. Another customization option is RTS=, which increases the row title space (the space for the width of the row title, including the vertical lines).
Let us look another example where we can change the names of the variables in the Proc Tabulate Procedure.

#Solution:

title "Descriptive Statistics";
proc tabulate data=A15011.A11_college format=6.1;
class Gender;
var GPA;
tables GPA*(n*f=4.
mean min max),
Gender all;
keylabel n = 'Number'
all = 'Total'
mean = 'Average'
min = 'Minimum'
max = 'Maximum';
run;

#Output:

'
In the above output we can see that, the variable name "n" is changed as Number,"min" is changed as "Minimum" and similarly for max and avg. Thus usiing Proc Tabulate we can alter the table based on our needs to report the output.

4. Introduction to ODS

One of the most important changes in SAS, starting with Version 7, was the introduction of the Output Delivery System, abbreviated as ODS. Prior to ODS, each SAS procedure
produced its own unique output, usually featuring a non-proportional font.

Each SAS procedure creates output objects that can be sent to such destinations as HTML, RTF, PDF, and SAS data sets.There is now a separation between the results produced by each procedure and the delivery of this information. Not only can you send your SAS output to all of these formats, you can, if you are brave enough, customize the output’s fonts, colors, size, and
layout. Finally, you can now capture virtually every piece of SAS output to a SAS data
set for further processing.

#Problem:

Run the following program, sending the output to an HTML file. Issue the appropriate commands to prevent SAS from creating a listing file.

title "Sending Output to an HTML File";
proc print data=learn.college(obs=8) noobs;
run;
proc means data=learn.college n mean maxdec=2;
var GPA ClassRank;
run;


#Solution:

options fmtsearch=(A15011);
ods listing close;
ods html file = '/folders/myfolders/prob19_1.html';
title "Sending Output to an HTML File";
proc print data=A15011.A11_college(obs=8) noobs;
run;
proc means data=A15011.A11_college n mean maxdec=2;
var GPA ClassRank;
run;
ods html close;
ods listing;

#Output:





#Explanation:

In the above example we tried to get the output as HTML page rather than the normal listing output. If you do not want a listing style output, use the ODS statement before the
ODS HTML FILE statement. Next. to get the output as an HTML file, we use the ODS html statement to give a local path so that tho output can be saved in that place as an HTML file. Finally, If you want to reinstate the listing output, use "ods listing" which will reinstate the listing output.

5. Generating High-Quality Graphics

In this post we speaks about some basic concepts behind SAS/GRAPH software. First you need to have SAS/GRAPH installed on your computer. Without it, you are relegated to using the older style “line printer” type plots using such procedures as PROC CHART and PROC PLOT.
These procedures are fine if you want a quick look at your data in graphical form; however, they are not suitable for presentations.

The appearance of graphs and charts is controlled by graphics options and global
statements such as SYMBOL and PATTERN. Options that are set using these statements
act somewhat like titles created using TITLE statements. That is, they remain in effect
until you change them and they are additive. For example, if you already have dots
selected as your plotting symbols, with the color set to black, and you change the color to
red, your plots display with red dots. Lets do some problems.

#Problem:

Using the SAS data set Bicycles, we want to produce two vertical bar charts showing frequencies for Country and Model. Use the PATTERN option VALUE=empty.

#Dataset:

*Data set BICYCLES;
data learn.bicycles;
   input Country  & $25.
         Model    & $14.
         Manuf    : $10.
         Units    :   5.
         UnitCost :  comma8.;
   TotalSales = (Units * UnitCost) / 1000;
   format UnitCost TotalSales dollar10.;
   label TotalSales = "Sales in Thousands"
         Manuf = "Manufacturer";
datalines;
USA  Road Bike  Trek 5000 $2,200
USA  Road Bike  Cannondale 2000 $2,100
USA  Mountain Bike  Trek 6000 $1,200
USA  Mountain Bike  Cannondale 4000 $2,700
USA  Hybrid  Trek 4500 $650
France  Road Bike  Trek 3400 $2,500
France  Road Bike  Cannondale 900 $3,700
France  Mountain Bike  Trek 5600 $1,300
France  Mountain Bike  Cannondale  800 $1,899
France  Hybrid  Trek 1100 $540
United Kingdom  Road Bike  Trek 2444 $2,100
United Kingdom  Road Bike  Cannondale  1200 $2,123
United Kingdom  Hybrid  Trek 800 $490
United Kingdom  Hybrid  Cannondale 500 $880
United Kingdom  Mountain Bike  Trek 1211 $1,121
Italy  Hybrid  Trek 700 $690
Italy  Road Bike  Trek 4500  $2,890
Italy  Mountain Bike  Trek 3400  $1,877
;


#Solution:

title Freq of countries;
proc sgplot data=A15011.A11_bicycles;
    vbar Country;
    xaxis label='Country';
run;
 
title 'Freq of Models';
proc sgplot data=A15011.A11_bicycles;
    hbar Model;
    xaxis label='Count';
run;

#Output:




#Explanation:


There are lot of normal type of charts such as Proc Plot/Chart as said before, but it wont look like a feel good visuals. So creating a good graphical content there are lot of specific procedures such as gchart, gplot etc., which will gives some good graphical outputs. In the above example we used GPLOT procedure which produced the graphical content for your data. The VBAR and HBAR states abou the position of the graph like vertical or horizontal. Also we can give names for the axis xaxis and yaxis statement. Try the same graph using GCHART.

6. Proc FREQ

PROC FREQ can be used to count frequencies of both character and numeric variables, in one-way, two-way, and three-way tables. In addition, you can use PROC FREQ to create output data sets containing counts and percentages. Finally, if you are statistically inclined, you can use this procedure to compute various statistics such as chi-square, odds ratio, and relative risk.

#Problem:

Using the SAS data set Blood, we will generate one-way frequencies for the variables Gender, BloodType, and AgeGroup.

#Dataset:

Used in the previous example.

#Solution:

title "One-way Frequencies from BLOOD Data Set";
proc freq data=A15011.A11_blood;
tables Gender BloodType AgeGroup / nocum nopercent;
run;

#Output:




#Explanation:
Here using the Proc freq procedure we can computes counts for each unique value of a variable. Here the TABLES statement to list the variables for which you want to compute
frequencies. Thus, in this example we are trying to calculate the frequencies for the variables Gender, Blood type and Age group. Secondly, w have used some option like NOCUM and NOPERCENT which tells PROC FREQ not to include the two cumulative statistics columns and percentages in the output, respectively.

The above example is single way frequency table and we can also produce two way or three way frequency tables. The below example shows how to produce three way frequency table. By using the college dataset we can build a three way freq table.

proc freq data=A15011.A11_college;
tables Gender*Scholarship*SchoolSize;
run;

In the above program we try to get a freq table for Gender, Scholarship and School size. To built a multi way freq table we have to use (*) symbol between the variables. The output for the above program will looks like below.

#Output:



From the output, we got Gender wise 2 tables and each table shows whether they have scholarship or not and it is further classified based on the school type. Thus we can easily get the table format which will help us to classify based on the information we needed.

Friday, 2 October 2015

Welcome to SAS


Learning new things will help you to equip in this fast moving world. But writing a blog about your experience of new learning not only help others but it helps you as well in future as a reference for your work. In the competitive world every company should innovate themselves very frequently to stay ahead of their competition. Also they need to study about the changing market conditions or customers to suffice their needs. Lot of time taking the decision is very hard and it also get failed since we are all take the decision based on our experience. There is no way to support your decision with strong evidence.

On the other side you can make use of the data which is increasing day to day. Identifying the valuable insights from the data helps to take a valid decision which helps to grow your company. There are lot of tools available to analyze the big big data. I wills start to write about SAS which is a standard tool used by most of the organisation.

Learning SAS is not a big deals since it will be easier than other complex program languages. The code used here look like a normal English language and those who don't have a programming experience can also easy take this tool to learn. As a first step to learn SAS, I will start from one of the basic book " Learning SAS by examples" - written by Ron Cody. Here I will try to post some of the problems given in the books.

1. 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 A15011.A11_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 A15011 "/folders/myfolders";

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


data A15011.A11_school1;
*subsetting the school datast;
set A15011.A11_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=A15011.A11_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.

2. Do loops

In the previous post, we saw if else condition. In this post, we can see how can we improve programming using do loop. Some times we come up with a situation where we should use two or more IF statements for the same conditions. But we can avoid this by using DO and END statements where we can test a condition at first and then perform several actions. We will see this by the below examples.

#Problem:
There are three speed-reading methods(A, B and C) and we are assigning 10 subjects to each of the three methods. The results are given below in three lines of reading speeds, each line represents the results from each of the three methods.

250 255 256 300 244 268 301 322 256 333
267 275 256 320 250 340 345 290 280 300
350 350 340 290 377 401 380 310 299 399

Now, we want each observation should contain Method A,B or C and score. There should be 30 observation in the data set.

#Solution:
data A15011.A11_method;
*using Do loop assigning three methods and then the 10 subjects;
do method = 'method A','method B', 'method C';
do i = 1 to 10;
* @ symbol tells SAS more data to be added for the method;
input score @;
ouput;
end;
end;
drop i;
datalines;
250 255 256 300 244 268 301 322 256 333
267 275 256 320 250 340 345 290 280 300
350 350 340 290 377 401 380 310 299 399
;
proc print data=A15011.A11_method;
run;

In the above program we are using are using nested Do loop to assign 10 observations for each method. In first do loop SAS creates "Method A" and it will go to the next Do loop and which denotes there are totally ten subjects. When SAS starts to read the datalines it will read the 10 results in the first for method A. This is done because the @ symbol in the input line tell SAS there are more observation to add, so that SAS don't go for the next line. The below output shows both using @ symbol and without it.

#Output:

With @ symbol











                             Without @ Symbol



















#Learning:
So now we know that when and how to use Do loops and why it is efficient than IF statement. Also we learned about the nested DO loop. Moreover we now know how to read more data when it is present in the single line (by @ symbol).

3. SAS Dates

SAS normally stores the date into a single number—the number of days from January 1, 1960. Dates after January 1, 1960, are positive integers; dates before January 1, 1960, are negative integers. The below are the some of the example how SAS stores the data.
December 31, 1959    -1

       June 15, 2006             16,967
      October 21, 1950        -3,359
To avoid these we can use SAS date format  to display the date correctly in the output. There are few Date formats which we can used based on your need. Two very popular date formats are DATE9. and MMDDYY10. Also there is some difference in reading two digit year and four digit year in SAS. SAS can read four digit year flawlessly but for two year you have to specify the YEARCUTOFF option.The default value for this option is 1920 in SAS 8 and SAS®9. This value determines the start of a 100-year interval that SAS uses when it encounters a two-digit year. Now let us do some problems in the dates.

#Problem:
The below data contains three dates, the first two in the form mm/dd/yyyy descenders and the last in the form ddmmmyyyy. We have to name the three date variables Date1, Date2, and Date3. Also we have to format all three using the MMDDYY10. format. Also we can see how to include the number of years from Date1 to Date2 (Year12) and the number of
years from Date2 to Date3 (Year23) and finally we round these years to the nearest number.

01/03/1950 01/03/1960 03Jan1970
05/15/2000 05/15/2002 15May2003
10/10/1998 11/12/2000 25Dec2005


# Solution:
data A15011.A11_dates;
* using the date informats;
input Date1 : mmddyy10.
Date2 : mmddyy10.
Date3 : date9.;
*Using yrdif function to compute number of years between two dates;
*By giving actual we get the exact number of days;
Year1-2 = round(yrdif(Date1,Date2,'Actual'));
Year2-3 = round(yrdif(Date2,Date3,'Actual'));
format Date1-Date3 mmddyy10.;
datalines;
01/03/1950 01/03/1960 03Jan1970
05/15/2000 05/15/2002 15May2003
10/10/1998 11/12/2000 25Dec2005
;
Proc Print data=A15011.A11_threedates;
run;


#Output:


# Learning and reading the data from the output:           
In the above program we used two date informats (mmddyy10. & date9.). This tell SAS that how we read the data from the datalines. Don't forget to use . after the format. Then we use YRDIF function which is help to calculate the difference between the two dates and ACTUAL helps to get the exact difference which include the leap year. Finally we use formats which is different from informats. In formats we tell SAS how to write the data in output.

4. Sub-setting SAS data sets 

Subsetting SAS dataset is using some conditions and selecting observation from one dataset and creating the other. This may be useful when one want to work a particular set of observation rather than working the whole data. Moreover, this will help us to keep the original file undisturbed. In this post we will see how to subset the data from one dataset to the other .

#Problem:
We want to create a dataset from the hospital data (given the Ron cody book) where the admission data falls on Monday and the year is 2002. We also want to know the age of the patient as of the admission date.

Hospital Data-set:

data A15011.A11_hosp;
   do j = 1 to 1000;
      AdmitDate = int(ranuni(1234)*1200 + 15500);
      quarter = intck('qtr','01jan2002'd,AdmitDate);
      do i = 1 to quarter;
         if ranuni(0) lt .1 and weekday(AdmitDate) eq 1 then
            AdmitDate = AdmitDate + 1;
         if ranuni(0) lt .1 and weekday(AdmitDate) eq 7 then
            AdmitDate = AdmitDate - int(3*ranuni(0) + 1);
         DOB = int(25000*Ranuni(0) + '01jan1920'd);
         DischrDate = AdmitDate + abs(10*rannor(0) + 1);
         Subject + 1;
         output;
      end;
   end;
   drop i j;
   format AdmitDate DOB DischrDate mmddyy10.;
run;

#Solution:

data A15011.A11_monday02;
*subsetting the data hosp;
set A15011.A11_hosp;
where year(AdmitDate) eq 2002 and
weekday(AdmitDate) eq 2;
Age = round(yrdif(DOB,AdmitDate,'Actual'));
run;
proc print data=A15011.A11_monday02;
run;

#Output:















# About the program and Learning:
In this program we subset the original Hosp dataset to a new called monday02. This can be done by using SET function. The set function helps us to subset the observation from the original dataset. By giving any particular condition next to set function helos us to get the particular data or if we need the whole data we simply use the set function alone. In this programm we also used WEEKDAY function which helps us to compute the day of the week from the SAS date. Then we used yrdif and actual which we learned already.

5. Using Numeric functions

There are lot mathematical function that can be done through SAS. Starting from rounding numbers, computing dates from month-day-year values, summing and averaging the values of SAS variables, and hundreds of other tasks can be done in SAS. In this post we can see some of the numeric function by doing in SAS.

#Problem:
We want to compute the body mass index (BMI) from the health data set. Also we want to create four other variables based on BMI: 1) BMIRound is the BMI rounded to the nearest integer, 2)BMITenth is the BMI rounded to the nearest tenth, 3) BMIGroup is the BMI rounded to the nearest 5, and 4) BMITrunc is the BMI with a fractional amount truncated.

#Data set:
data A15011.A11_health;
   input Subj : $3.
         Height
         Weight;
datalines;
001 68 155
003 74 250
004 63 110
005 60 95
;
#Solution:
data A15011.A11_health1;
set A15011.A11_health;
BMI = (Weight/2.2) / (Height*.0254)**2;
BMIRound = round(BMI);
BMIRound_tenth = round(BMI,.1);
BMIGroup = round(BMI,5);
BMITrunc = int(BMI);
run;
Proc print data=A15011.A11_health1;
run;

#Output:



# Explanation and learning:
As seen in the previous posts, first we are sub-setting the data set from health to health1. Then we use the formula for BMI which is defined as the weight in kilograms divided by the height (in meters) squared. Then we use the round function with (.1) which denotes the nearest tenth and vice versa.

6. Working with Character function

In this post we will see character strings, take strings apart and put them back together again, and remove selected characters from a string. We can remove classes of characters, such as digits, punctuation marks, or space characters and even we can match between the two characters. Lets see this by some examples.

#Problem:
Using the data set Mixed, we want to the create following new variables:
a. NameLow – Name in lowercase
b. NameProp – Name in proper case
c. NameHard – Name in proper case without using the PROPCASE function

#Data set:
data A15011.A11_mixed;
   input Name & $20. ID;
datalines;
Daniel Fields  123
Patrice Helms  233
Thomas chien  998
;
Proc print data=A15011.A11_mixed;
run;

#Solution:
data A15011.A11_mixed1;
set A15011.A11_mixed;
length First Last $ 15 NameHard $ 20;
NameLow = lowcase(Name);
NameProp = propcase(Name);
First = lowcase(scan(Name,1,' '));
Last = lowcase(scan(Name,2,' '));
substr(First,1,1) = upcase(substr(First,1,1));
substr(Last,1,1) = upcase(substr(Last,1,1));
NameHard = catx(' ',First,Last);
drop First Last;
run;

#Output:



# Learning:
In this program we learned two new SAS functions called lowcase and Propcase. Also we used the substr function and how to use them in the SAS program.

7. Arrays in SAS

SAS arrays are a collection of elements (usually SAS variables) that allow you to write SAS statements referencing this group of variables. SAS arrays are different from arrays in many other programming languages. They do not hold values, and they convenient manner. In this post we can see some problem based on arrays.

#Problem:
Using the SAS data set Nines, create a SAS data set, where all values of 999 are replaced by SAS missing values. Do this without explicitly naming the numeric variables in data set Nines.

#Data set:
data A15011.A11_nines;
   infile datalines missover;
   input x y z (Char1-Char3)(:$1.) a1-a5;
datalines;
1 2 3 a b c 99 88 77 66 55
2 999 999 d c e 999 7 999
10 20 999 b b b 999 999 999 33 44
;
proc print data=A15011.A11_nines; run;

#Solution:   
data A15011.A11_nines1;
set A15011.A11_nines;
array nums{*} _numeric_;
do i = 1 to dim(nums);
if nums{i} = 999 then
call missing(nums{i});
end;
drop i;
run;
proc print data=A15011.A11_nines1;
run;

#Output:




#Learning :
In this program we get the idea about array and how it works in SAS. We used the do loop and dim function. Here we called missing value wherever 999 is present in the data set. 

8. Listing the observation using proc print

In this post we will see how to list the observations in a SAS data set using the PRINT procedure (PROC PRINT). Also we add some options and statements to this procedure to
allow you more control over what is displayed.

#Problem:
We want to list first 10 observations in data set Blood. Include only the variables Subject, WBC (white blood cell), RBC (red blood cell), and Chol. Label the last three variables “White Blood Cells,” “Red Blood Cells,” and “Cholesterol,” respectively. Omit the Obs column, and place Subject in the first column.

Blood data set: https://www.dropbox.com/s/9wq9gdqk99981n3/blood.txt?dl=0

#Solution:
proc print data=learn.blood(obs=10) label;
id Subject;
var WBC RBC Chol;
label WBC = 'White Blood Cells'
RBC = 'Red Blood Cells'
Chol = 'Cholesterol';
run;

#Output:




#Explanation and learning:
In the proc print step we are saying to the SAS that print first 10 observation alone along with the labels. Also we make the subject as the first column by using ID keyword. By giving the label for each variable SAS print the label name instead of the variable name in the output.

9. Customizing your reports

Although you can customize the output produced by PROC PRINT, there are times when you need a bit more control over the appearance of your report. PROC REPORT was
developed to fit this need. Not only can you control the appearance of every column of
your report, you can produce summary reports as well as detail listings. Lets see using PROC Report in the examples.

#Problem:
By using the same blood data set fro the previous post we want to produce a summary report showing the average WBC and RBC count for each value of Gender as well as an overall average.

#Solution:
title "Statistics from BLOOD by Gender";
proc report data=A15011.A11_blood nowd headline;
column Gender WBC RBC;
define Gender / group width=6;
define WBC / analysis mean "Average WBC"
width=7 format=comma6.0;
define RBC / analysis mean "Average RBC"
width=7 format=5.2;
rbreak after / dol summarize;
run;
quit;


#Output:





#Learning:
The title statement tells SAS to print the output with the given title. Also we use tell the SAS as how much the width we need for the column and what format the output should look like.