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.
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.
#Dataset:
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.
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.
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 A 92 95
12 B 88 88
13 C 78 75
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;
*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.
#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).
#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.
#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.
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.December 31, 1959 -1
June 15, 2006 16,967October 21, 1950 -3,359
#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.
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:
#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.
#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:
#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:
#Solution:
#Output:
# Learning:
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:
#Solution:
#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.
#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:
#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.
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:
#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.
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.











No comments:
Post a Comment