SAS programming
Introduction to SAS
Accessing the SAS System
SAS Basic Components
Writing a Basis SAS Program
SAS Syntax
Accessing Data in SAS Libraries
SAS Data Components
SAS Naming Conventions
Types of SAS Variables
What is SAS?
Who uses SAS
What SAS can do?
Statistical Analysis System
Developed by A.J.Barr & Jim Goodnight
Commercial software at 1976
New version 9.4 for PC
Financial Industry/Telecom Industry/Retail Industry
Medical/Pharmaceutical Industry
Universities/Government Departments
SAS is the undisputed leader in analytics.
90 of the top 100 Fortune Global 500 use SAS.
Can’t think of any industries that didn’t use SAS
Data entry
SAS viewer can works as spread sheet.
Storage
Huge data can be stored in SAS system.
Data access and output
Large variety of data files can be read into SAS.
Data cleaning
Powerful statements and step combinations for data cleaning
Data manipulation/transformation
Excellent performance in handing complex data manipulation and management
Data analysis
Statistical description
Basic statistical analysis including parameter estimate and hypothesis test
Advanced statistical analysis, including modeling and prediction
Data report
Routine data summarization
Creating summary tables
Creating routine summary reports
Report graphics
ODS enhances easy linkage to a variety of format: .csv .txt .doc .pdf .html .rtf
document
Present
Future
SAS/SQL/Tableau
R/Python
Business Intelligence Business Analytics Reporting Dashboard KPIs/Metrics Model(Explanatory)
Data Science Predictive Modeling Machine learning AI
What is the difference between base SAS and SAS enterprise guide?
Both the tools have a similar format and usage. The only difference being SAS Enterprise guide is the graphical user interface of Base SAS. SAS Enterprise guide is much easier to use and is modular in nature.
Pros of using both Base SAS and SAS Enterprise guide:
SAS Enterprise guide
1.
EG is more common in firms with a smaller team of analytics. This is because programs on EG are far more understandable by a person who is new to the firm. Given the high attrition rate in analytics industry, it becomes very essential for such firm to hedge their risk by using the SAS Enterprise guide instead of Base SAS.
2.
You develop a certain traditional routine much faster on EG than on Base SAS.
3.
It is much easier to comprehend the flow using EG.
Base SAS
1.
It is much easier to code on base SAS in case the logic of code is very complex.
2.
Base SAS is much faster as compare to EG.
3.
It is much easier to modify a code on Base SAS than on EG.
4.
Using Macros makes coding in Base SAS much easier than SAS EG
Both Base SAS and EG have their own pros and cons. The best recommended strategy is to use both. If you want to make a traditional query, use SAS EG to generate automated code. Now copy this code to make it macronized and generalized using Base SAS. The macro adds a new dimension to the codes which helps you generalize the code and avoid hard entered data
20/Day One
Five Windows in SAS:
Program Editor
Log
Output
Results
Explorer
What are the basic components of SAS Software?
There are five basic SAS windows: the Results and Explorer windows, and three programming windows: Editor, Log, and Output. In the Windows operating environment a sixth window, the Results Viewer appears if you run a program that generates printable results.
Program Editor
You can use the Program Editor window to :
access and edit existing SAS programs
write new SAS programs
submit SAS programs
save SAS programs to a file
Log
lists any errors made in running the SAS program;
lists some notes indicating how many variables and observations are contained in the data set;
trace the processing of your Program.
OUTPUT : displays unchangeable results.
Output In the z/OS operating environment, all tabular results will appear in the Output window. By default, in the Windows and UNIX environments, nothing appears in the Output window. But if you turn on the LISTING destination (see section 5.4), then results will appear in the Output window.
Results Viewer In the Windows operating environment, if your program generates any printable results, then the Results Viewer window will open and display the results.
When you have a lot of output, the Results window can be very helpful. The Results window is like a table of contents for your output. It lists each procedure that produces output, and if you open or expand the procedure in the Results tree, you can see each part of the procedure output. Expand the results tree, by clicking the plus (+) signs, or by right-clicking the result and selecting Expand All.
Results The Results window is like a table of contents for your Output and Results Viewer windows; the results tree lists each part of your results in an outline form.
SAS default files:
SAS dataset .sas7bdat
SAS program .sas
SAS output .lst
SAS log .log
SAS format file .sas7bcat
SAS Enterprise Guide project - .egp
When you first open SAS session, you see a navigation pane on the left and work area on the right
Navigation pane : access to libraries and folders that contain your data files
Work area : program window with tabs for your SAS codes, log and results(output)
SAS programs are constructed from two basic building blocks:
DATA Steps
PROC Steps
DATA and PROC steps are made up of statements. A step may have as few as one or as many as hundreds of statements.
DATA steps execute line by line and observation by observation. By default, SAS executes line one of your DATA step before it executes line two, and line two before line three, and so on.
What are the two basic building blocks of SAS program?
Two basic building blocks
Data Step
Typically create or modify the SAStables.
Can use Data Step put your data
Into SAS tables
Compute values
Check for and correct errors in your data
Produce new data by sub-setting, merging, and updating existing tables.
Procedure Step: enable you to process and analyse data in a table and present you data.
You can use Procedure to
Summarize
Sort
List data
Produce descriptive statistics
Generate reports andgraphs
RUN; Statement
Use “RUN;” statement to complete both DATA and PROC steps
“RUN;” statement tells SAS to execute the code.
Now let’s look at individual statements in each steps.
Each Step in SAS program is made up of a sequence of statements.
DATA EUROPEANCAR;
SET Sashelp.CARS;
WHERE Origin = "Europe";
RUN;
SAS statement usually begins with a keyword and end with a semicolon.
It begins with the keyword “DATA” followed by the name of the table to be created “EUROPEANCAR” .
Because this program is reading a SAS table, next you use the “SET” statement to specify the table “Sashelp.CARS” .
Following the “SET” statement, the data step can contains additional programming statements.
In this example a “WHERE” statement specifies the new table , ”EUROPEANCAR“ , will include those rows where the value of origin is “Europe”.
The step end with the “RUN;“ statement.
Now let’s look at the “PROC “ step, in this case a “PRINT “ procedure.
It begins with the key word “PROC PRINT “ followed by “DATA = the name of the table used in the report, ”EUROPEANCAR”.( it is optional i.e. If you don’t mention data= ”EUROPEANCAR” , this procedure will execute for last data that you execute
Let’s submit the code and see what happens. Click “RUN;”
SAS displays the results immediately after the code has run.
Every time you submit a SAS program, SAS writes messages in your log. Many SAS programmers ignore the SAS log and go straight to the output. That’s understandable, but dangerous. It is possible—and sooner or later it happens to all of us—to get bogus results that look fine in the output. The only way to know they are bad is to check the SAS log. Just because it runs doesn’t mean it’s right. You must check SAS log after any execution to make sure every thingis fine.
If there were error messages, they would appear in the log, indicating where SAS got confused and what action it took. You may also find warnings and other types of notes which sometimes indicate errors and other times just provide useful information.
Reading the SAS Log
There are two sets of note in the log, one for each step in the program.
The first set of notes follows the code for “DATA” step and indicates that SAS reads 123 rows from Sashelp.cars where origin =“Europe” and created a table name “EUROPEANCAR” in a temporary library name called “work”.
The second set of notes follows the code for the “PROCEDURE” step.SAS reads the 123 rows from “” and generate a list report.
As I mentioned before, SAS programs are constructed from two basic building blocks:
-DATASteps
-PROCSteps
DATA steps read and modify data while PROC steps analyze data, perform utility functions, or print reports.
43/Day One
As you read this table, keep in mind that it is a simplification. Because SAS is so flexible, the differences between DATA and PROC steps are, in reality, more blurry. The table above is not meant to imply that PROC steps never create SAS data sets (most do), or that DATA steps never produce reports (they can). Nonetheless, you will find it much easier to write SAS programs if you understand the basic functions of DATA and PROC steps.
A step ends when SAS encounters a new step (marked by a DATA or PROC statement); a RUN, QUIT, STOP, or ABORT statement; or, if you are running in batch mode, the end of the program. RUN statements tell SAS to run all the preceding lines of the step and are among those rare, global statements that are not part of a DATA or PROC step. In the following program, SAS knows that the DATA step has ended when it reaches the PROC statement. The PROC step ends with a RUN statement, which coincides with the end of the program.
DATA steps have an implicit, built-in-loop , and SAS does it automatically.
WhileDATAstepsexecutelinebyline,theyalsoexecuteobservationbyobservation.
ThatmeansSAStakesfirstobservationandrunsitallthewaythroughtheDATAstep(linebyline)beforeloopingbacktopickupthesecondobservation.
In this way, SAS sees only one
SAS statements :
usually begin with an identifying keyword
always end with asemicolon
SAS Statements are free-format
One or more blanks or special characters can be used to separate words
They can begin and end in any column
A single statement can span multiple lines (as long as you don’t split words in two).
Several statement can be on the same line
SAS statements can be in upper- or lowercase.
good spacing makes the program easier to read.
SAS programming statement are easier to read if you
begin DATA, PROC
and RUN statement in column one
and indent the other statements .
Any data set in SAS has two levels when you call it, first library name then dot after dot you should specify name of data set.
If you skip name of library by default it is work library, the only temporary library.
Before you can use a SAS data set, you have to tell SAS where to find it. You do that by setting up a SAS library. A SAS library is simply a location where SAS data sets (as well as other types of SAS files) are stored. Depending on your operating environment, a SAS library might be a folder or directory on your computer, or it might be a physical location like a hard drive, flash drive, or CD.
DATA EUROPEANCAR;
SET Sashelp.CARS;
WHERE Origin = "Europe";
proc print data= EUROPEANCAR ;
run;
Library name
Data set name
Work.EUROPEANCAR
When you open the Active Libraries window, you will see at least three libraries: SASHELP, SASUSER, and WORK. You may have other libraries for specific SAS products (such as the MAPS library for SAS/GRAPH software), or libraries that have been set up by you or someone you work with. The SASHELP library contains information that controls your SAS session along with sample SAS data sets. The WORK library is a the only temporary storage location for SAS data sets. It is also the default library. If you create a SAS data set without specifying a library, SAS will put it in the WORK library, and then delete it when you end your session. If you make changes to the default settings for the SAS windowing environment, this information will be stored in the SASUSER library. You can also store SAS data sets, SAS programs, and other SAS files in the SASUSER library. However, many people prefer to create a new library,their own library, for their SAS files.
Active Libraries window
3
1. Intrductin t SAS
2.
Accessing the SAS System
3.
SAS Basic Cmpnents
4.
Writing a Basis SAS Prgram
5.
SAS Syntax
6.
Accessing Data in SAS Libraries
7.
SAS Data Cmpnents
8.
SAS Naming Cnventins
9.
Types f SAS Variables
5
What is SAS?
Wh uses SAS
What SAS can d?
6
Statistical Analysis System
Develped by A.J.Barr & Jim Gdnight
Cmmercial sftware at 1976
New versin 9.4 fr PC
7
Financial Industry/Telecm Industry/Retail Industry
Medical/Pharmaceutical Industry
Universities/Gvernment Departments
SAS is the undisputed leader in analytics.
90 f the tp 100 Frtune Glbal 500 use SAS.
Can’t think f any industries that didn’t use SAS
8
Turning Data int Infrmatin
Data
DATA
Step
SAS
Data Sets
PRC
Steps
Infrmatin
9
Data entry
SAS viewer can wrks as spread sheet.
Strage
Huge data can be stred in SAS system.
Data access and utput
Large variety f data files can be read int SAS.
10
Data cleaning
Pwerful statements and step cmbinatins fr data cleaning
Data manipulatin/transfrmatin
Excellent perfrmance in handing cmplex data manipulatin and management
11
Data analysis
Statistical descriptin
Basic statistical analysis including parameter estimate and hypthesis test
Advanced statistical analysis, including mdeling and predictin
12
Data reprt
Rutine data summarizatin
Creating summary tables
Creating rutine summary reprts
Reprt graphics
DS enhances easy linkage t a variety f frmat: .csv .txt .dc .pdf .html .rtf
dcument
14
Past
Present
Future
SAS/SQL/Tableau
R/Pythn
Business Intelligence Business Analytics Reprting Dashbard KPIs/Metrics Mdel(Explanatry)
Data Science Predictive Mdeling Machine learning AI
What is the difference between base SAS and SAS enterprise guide?
Bth the tls have a similar frmat and usage. The nly difference being SAS Enterprise guide is the graphical user interface f Base SAS. SAS Enterprise guide is much easier t use and is mdular in nature.
Prs f using bth Base SAS and SAS Enterprise guide:
SAS Enterprise guide
1.
EG is mre cmmn in firms with a smaller team f analytics. This is because prgrams n EG are far mre understandable by a persn wh is new t the firm. Given the high attritin rate in analytics industry, it becmes very essential fr such firm t hedge their risk by using the SAS Enterprise guide instead f Base SAS.
2.
Yu develp a certain traditinal rutine much faster n EG than n Base SAS.
3.
It is much easier t cmprehend the flw using EG.
Base SAS
1.
It is much easier t cde n base SAS in case the lgic f cde is very cmplex.
2.
Base SAS is much faster as cmpare t EG.
3.
It is much easier t mdify a cde n Base SAS than n EG.
4.
Using Macrs makes cding in Base SAS much easier than SAS EG
Bth Base SAS and EG have their wn prs and cns. The best recmmended strategy is t use bth. If yu want t make a traditinal query, use SAS EG t generate autmated cde. Nw cpy this cde t make it macrnized and generalized using Base SAS. The macr adds a new dimensin t the cdes which helps yu generalize the cde and avid hard entered data
17
Accessing the SAS System
Basic cmpnents f SAS
Writing a basic SAS prgram
Editing my first prgram
18
Start SAS Sessin Methd 1:
Duble click the SAS icn
Methd 2:
Start
All Prgrams
SAS
SAS 9.4
What are tw ways yu can access SAS System?
20
Five Windws in SAS:
Prgram Editr
Lg
utput
Results
Explrer
What are the basic cmpnents f SAS Sftware?
There are five basic SAS windws: the Results and Explrer windws, and three prgramming windws: Editr, Lg, and utput. In the Windws perating envirnment a sixth windw, the Results Viewer appears if yu run a prgram that generates printable results.
21
Prgram Editr
Yu can use the Prgram Editr windw t :
access and edit existing SAS prgrams
write new SAS prgrams
submit SAS prgrams
save SAS prgrams t a file
22
Lg
lists any errrs made in running the SAS prgram;
lists sme ntes indicating hw many variables and bservatins are cntained in the data set;
trace the prcessing f yur Prgram.
23
UTPUT : displays unchangeable results.
utput In the z/S perating envirnment, all tabular results will appear in the utput windw. By default, in the Windws and UNIX envirnments, nthing appears in the utput windw. But if yu turn n the LISTING destinatin (see sectin 5.4), then results will appear in the utput windw.
23
Results Viewer In the Windws perating envirnment, if yur prgram generates any printable results, then the Results Viewer windw will pen and display the results.
When yu have a lt f utput, the Results windw can be very helpful. The Results windw is like a table f cntents fr yur utput. It lists each prcedure that prduces utput, and if yu pen r expand the prcedure in the Results tree, yu can see each part f the prcedure utput. Expand the results tree, by clicking the plus (+) signs, r by rightclicking the result and selecting Expand All.
Results The Results windw is like a table f cntents fr yur utput and Results Viewer windws; the results tree lists each part f yur results in an utline frm.
23
EXPLRER
prvides the same functins as MS Explrer
views and manages yur SAS files, which are stred in libraries.
24
SAS default files:
SAS dataset
SAS prgram
SAS utput
SAS lg
SAS frmat file
.sas7bdat
.sas
.lst
.lg
.sas7bcat
SAS Enterprise Guide prject .egp
25
When yu first pen SAS sessin, yu see a navigatin pane n the left and wrk area n the right
Navigatin pane : access t libraries and flders that cntain yur data files
Wrk area : prgram windw with tabs fr yur SAS cdes, lg and results(utput)
28
SAS prgrams are cnstructed frm tw basic building blcks:
DATA Steps
PRC Steps
DATA and PRC steps are made up f statements. A step may have as few as ne r as many as hundreds f statements.
DATA steps execute line by line and bservatin by bservatin. By default, SAS executes line ne f yur DATA step befre it executes line tw, and line tw befre line three, and s n.
What are the tw basic building blcks f SAS prgram?
Tw basic building blcks
29
Data Step
Typically create r mdify the SAStables.
Can use Data Step put yur data
Int SAS tables
Cmpute values
Check fr and crrect errrs in yur data
Prduce new data by subsetting, merging, and updating existing tables.
30
Prcedure Step: enable yu t prcess and analyse data in a table and present yu data.
Yu can use Prcedure t
Summarize
Srt
List data
Prduce descriptive statistics
Generate reprts andgraphs
31
RUN; Statement
Use “RUN;” statement t cmplete bth DATA and PRC steps
“RUN;” statement tells SAS t execute the cde.
Nw let’s lk at individual statements in each steps.
Each Step in SAS prgram is made up f a sequence f statements.
32
DATA EURPEANCAR;
SET Sashelp.CARS;
WHERE rigin = "Eurpe";
RUN;
SAS statement usually begins with a keywrd and end with a semicln.
It begins with the keywrd “DATA” fllwed by the name f the table t be created “EURPEANCAR” .
Because this prgram is reading a SAS table, next yu use the “SET” statement t specify the table “Sashelp.CARS” .
34
Fllwing the “SET” statement, the data step can cntains additinal prgramming statements.
In this example a “WHERE” statement specifies the new table , ”EURPEANCAR“ , will include thse rws where the value f rigin is “Eurpe”.
The step end with the “RUN;“ statement.
37
Nw let’s lk at the “PRC “ step, in this case a “PRINT “ prcedure.
It begins with the key wrd “PRC PRINT “ fllwed by “DATA = the name f the table used in the reprt, ”EURPEANCAR”.( it is ptinal i.e. If yu dn’t mentin data= ”EURPEANCAR” , this prcedure will execute fr last data that yu execute
Let’s submit the cde and see what happens. Click “RUN;”
SAS displays the results immediately after the cde has run.
Every time yu submit a SAS prgram, SAS writes messages in yur lg. Many SAS prgrammers ignre the SAS lg and g straight t the utput. That’s understandable, but dangerus. It is pssible—and sner r later it happens t all f us—t get bgus results that lk fine in the utput. The nly way t knw they are bad is t check the SAS lg. Just because it runs desn’t mean it’s right. Yu must check SAS lg after any executin t make sure every thingis fine.
If there were errr messages, they wuld appear in the lg, indicating where SAS gt cnfused and what actin it tk. Yu may als find warnings and ther types f ntes which smetimes indicate errrs and ther times just prvide useful infrmatin.
Reading the SAS Lg
40
There are tw sets f nte in the lg, ne fr each step in the prgram.
The first set f ntes fllws the cde fr “DATA” step and indicates that SAS reads 123 rws frm Sashelp.cars where rigin =“Eurpe” and created a table name “EURPEANCAR” in a temprary library name called “wrk”.
The secnd set f ntes fllws the cde fr the “PRCEDURE” step.SAS reads the 123 rws frm “” and generate a list reprt.
42
As I mentined befre, SAS prgrams are cnstructed frm tw basic building blcks:
DATASteps
PRCSteps
DATA steps read and mdify data while PRC steps analyze data, perfrm utility functins, r print reprts.
43
As yu read this table, keep in mind that it is a simplificatin. Because SAS is s flexible, the differences between DATA and PRC steps are, in reality, mre blurry. The table abve is nt meant t imply that PRC steps never create SAS data sets (mst d), r that DATA steps never prduce reprts (they can). Nnetheless, yu will find it much easier t write SAS prgrams if yu understand the basic functins f DATA and PRC steps.
A step ends when SAS encunters a new step (marked by a DATA r PRC statement); a RUN, QUIT, STP, r ABRT statement; r, if yu are running in batch mde, the end f the prgram. RUN statements tell SAS t run all the preceding lines f the step and are amng thse rare, glbal statements that are nt part f a DATA r PRC step. In the fllwing prgram, SAS knws that the DATA step has ended when it reaches the PRC statement. The PRC step ends with a RUN statement, which cincides with the end f the prgram.
45
DATA steps have an implicit, builtinlp , and SAS des it autmatically.
WhileDATAstepsexecutelinebyline,theyalsexecutebservatinbybservatin.
ThatmeansSAStakesfirstbservatinandrunsitallthewaythrughtheDATAstep(linebyline)befrelpingbacktpickupthesecndbservatin.
In this way, SAS sees nly ne
47
SAS statements :
usually begin with an identifying keywrd
always end with asemicln
48
SAS Statements are freefrmat
ne r mre blanks r special characters can be used t separate wrds
They can begin and end in any clumn
A single statement can span multiple lines (as lng as yu dn’t split wrds in tw).
Several statement can be n the same line
SAS statements can be in upper r lwercase.
49
DATA EURPEANCAR;
SET
Sashelp.CARS;
WHERE rigin =
"Eurpe";
RUN;prc print data =eurpeancar;run;
Nte: Fr cunting number f statements cunt number f semicln.
50
Gd spacing makes the prgram easier t read.
SAS prgramming statement are easier t read if yu
begin DATA, PRC
and RUN statement in clumn ne
and indent the ther statements .
51
data distance_2;
d miles = 1 t 20;
kilmeters = miles * 1.61;
utput;
end;
run;
prc print data=distance_2;
run;
52
2 ways fr SAS cmments
Methd#1: /* cmment*/
Type /* t begin a cmment
Type yur cmment text
Type */ t end the cmment
Methd #2: * cmment;
Type * t begin a cmment
Type yur cmment text
Type ; t end the cmment
Hint: In the Micrsft Windws perating envirnment, if yu use the Enhanced Editr,
yu can cmment ut a blck f cde by highlighting the blck and then pressing CTRL and / (frward slash) tgether.
T uncmment a blck f cde, highlight the blck and press CTRL and SHIFT and / (frward slash) tgether.
Cmments T make yur prgrams mre understandable, yu can insert cmments int yur prgrams. It desn’t matter what yu put in yur cmments—SAS desn’t lk at it.
53
/*cnverts miles t kilmeters*/
data distance_2;
d miles = 1 t 20;/* this is a lp*/
kilmeters = miles * 1.61;
utput;
end;
run;
* see the result;
prc print data=distance_2;
run;
Since sme perating envirnments interpret a slash asterisk (/*) in the first clumn as the end f a jb, be careful when using this style f cmment nt t place it in the first clumn.
54
Syntax errrs include :
Misspelled keywrds
Missing r invalid punctuatin
Invalid ptins
57
Debugging a SAS Prgram
submit a SAS prgram
diagnse the errrs
crrect the prgram
submit the crrected SAS prgram
save the crrected prgram
Any data set in SAS has tw levels when yu call it, first library name then dt after dt yu shuld specify name f data set.
If yu skip name f library by default it is wrk library, the nly temprary library.
Befre yu can use a SAS data set, yu have t tell SAS where t find it. Yu d that by setting up a SAS library. A SAS library is simply a lcatin where SAS data sets (as well as ther types f SAS files) are stred. Depending n yur perating envirnment, a SAS library might be a flder r directry n yur cmputer, r it might be a physical lcatin like a hard drive, flash drive, r CD.
DATA EURPEANCAR;
SET Sashelp.CARS;
WHERE rigin = "Eurpe";
prc print data= EURPEANCAR ;
run;
Library name
Data set name
Wrk.EURPEANCAR
When yu pen the Active Libraries windw, yu will see at least three libraries: SASHELP, SASUSER, and WRK. Yu may have ther libraries fr specific SAS prducts (such as the MAPS library fr SAS/GRAPH sftware), r libraries that have been set up by yu r smene yu wrk with. The SASHELP library cntains infrmatin that cntrls yur SAS sessin alng with sample SAS data sets. The WRK library is a the nly temprary strage lcatin fr SAS data sets. It is als the default library. If yu create a SAS data set withut specifying a library, SAS will put it in the WRK library, and then delete it when yu end yur sessin. If yu make changes t the default settings fr the SAS windwing envirnment, this infrmatin will be stred in the SASUSER library. Yu can als stre SAS data sets, SAS prgrams, and ther SAS files in the SASUSER library. Hwever, many peple prefer t create a new library,their wn library, fr their SAS files.
Active Libraries windw
59
Yu can stre SAS files in either :
temprary r
permanent library
At the beginning f each sessin , SAS autmatically prvide ne temprary lib and at least ne permanent lib that yu can access.
i.e. If yu put yur data in wrk library (It is the nly temprary library, after clsing the SAS prgram yu can nt find that data in next time, but if yu put it in permanent library( any library except wrk library), yu can find that data later as well.
63
All SAS tables have tw level names.
First name is the name f the SAS library that cntains the SAS tables.
Secnd name is the name f the table.
These tw name are separated by a perid.
If yu dn’t mentin the name f library, by default it is in wrk library.
ratedata
=64
Hw des SAS knw where the library is lcated?
The name f the library is used as a shrtcut t pint t the physical lcatin f the library n yur perating system
T set up a library, all yu have t d is make up a name fr yur library and tell SAS where it is. There are several ways t d this including using the LIBNAME statement and using the New Library windw in the SAS windwing envirnment.
65
Assigning a libref (Methd#1) :user interface:
Explrer
Library
Right click
New
Yu can create new SAS libraries using the New Library windw. T pen this windw, either select Tls ► New Library frm the menu bar, r rightclick the Active Libraries windw and chse New frm the ppup menu. icn new library in up tlbar r Explrer windw Right click n Library New give the name fr example h1,enable at start up, chse yur path and k
Nte: In the New Library windw, type the name f the library yu want t create. This name is called a libref, which is shrt fr library reference. A libref must be 8 characters r fewer; start with a letter r underscre; and cntain nly letters, numerals, r underscres.
Nte: In the Path field, enter the cmplete path t the flder r directry where yu want yur data sets t be stred, r click the Brwse… buttn t navigate t the lcatin. If yu dn’t want t define yur library reference every time yu start up SAS, then check the Enable at startup bx. Click K and then yur new library reference will appear in the Active Libraries windw.
Librefs cannt be lnger than 8 characters while member names can be up t 32 characters lng.
DATA wrk.dublecentury; wrk dublecentury temprary
66
Assigning a libref (Methd #2)
LIBNAME statement
/*g t any drive fr example. Users\hmdra\Desktp\Metr Cllege_Teaching Materials\SAS\my exercise and create a flder fr example testn then cpy its address and cme back t sas and write the keywrd libname and give any name yu want as a libref fr example Hmd and then paste just the address in single r duble qutatin */
libname hmd 'C:\Users\hmdra\Desktp\Metr Cllege_Teaching Materials\SAS\my exercise\testn’;
Rules fr naming libref:
8 characters rfewer
Start with a letter r anunderscre
Cntain nly letters, numbers runderscres
Yu need t submit a LIBNAME statement nly nce during each SAS sessin .The libref remains in effect fr the duratin f that sessin. But the data that yu stred in that library exist fr ever until yu delete them, but in any sessinyu shuld say where that library is lcated .Yu can assign different name fr libref fr same lcatin and use it i.e.
The libref can change, but the member name( file name), and directry must the same.(A libref is just a nickname that crrespnds t the lcatin f a SAS data library. )
libname hmd 'C:\Users\hmdra\Desktp\Metr Cllege_Teaching Materials\SAS\my exercise\testn’;
=
libname h 'C:\Users\hmdra\Desktp\Metr Cllege_Teaching Materials\SAS\my exercise\testn’;
A LIBNAME statement cnsists f :
the keywrd LIBNAME.
the libref name that yu want t use.
the pathname that represents the physical lcatin f the library.
a semicln.
The fllwing LIBNAME statement assigns themydatalibref t yur shared flder. The directry that yu assciate with the libref must already exist befre yu can assign it t the libref.
libname mydata '/flders/myflders/';
Yu can submit the LIBNAME statement alne, r yu can add it t the tp f yur prgram s that it is run every time yu run the prgram.
If yu dn’t want t be bthered with setting up librefs and defining SAS libraries, but yu still want t use permanent SAS data sets, then yu can use direct referencing. Direct referencing still uses SAS libraries, but instead f defining the library yurself, yu let SAS d it fr yu. Like:
DATA 'c:\MySASLib\magnlia';
INFILE 'c:\MyRawData\Mag.dat';
INPUT ScientificName $ 114 CmmnName $ 1632 MaximumHeight
AgeBlm Type $ Clr $;
RUN;
When yu put qutatin marks arund yur data set name, yu are using direct referencing, and SAS creates a permanent SAS data set. Since yu haven't specified a libref, SAS makes up a libref fr yu. Yu dn’t need t knw the name f the libref that SAS makes up, but it is there and yu can see it in the Active Libraries windw.
Reading SAS data sets using direct referencing T read a permanent SAS data set using direct referencing, simply enclse the path and name fr the data set in qutatin marks wherever yu wuld use a SAS data set name. Fr example, t print the MAGNLIA data set, yu culd use the fllwing statements:
PRC PRINT DATA = 'c:\MySASLib\magnlia';
TITLE 'Magnlias';
RUN;
FYI
02Nv23 83
SAS System
Windws flder/Servers
Bridge (Library)
Accessing Data in SAS Libraries
Hw des SAS knw where the library is lcated?
The name f the library is used as a shrtcut t pint t the physical lcatin f the library n yur perating system.
T g back t the previus windw within Explrer, chse View ► Up ne level frm the menu bar, r click the Explrer windw t make it active, and then click the Up ne Level buttn n the tlbar.
Viewing Data Sets in the Viewtable Windw
When yu are writing prgrams, it is always a gd idea t check the data sets yu create t make sure they are crrect. Viewtable is ne way yu can lk at yur SAS data sets.
If yu dubleclick a library icn, SAS will pen a Cntents windw shwing yu all the SAS files in that particular library.
Cntents windw This windw shws the cntents f a library. SAS data sets are represented by an icn shwing a little table f data and a red ball.
If yu dubleclick a data set, SAS will pen a Viewtable windw shwing that data set.
Viewtable windw This windw allws yu t create, brwse, and edit data sets. When yu first pen SAS data sets, the data are in brwse mde s yu cannt make any changes. T switch t edit mde, select Edit ► Edit Mde frm the menu bar. Creating and editing data sets using Viewtable.
Changing clumn headings By default, Viewtable uses variable labels fr clumn headings, r, if a variable des nt have a label, the variable name is displayed. Smetimes yu may want t see the actual variable names instead f the labels. T d this, click the Viewtable windw t make it active, then select View ► Clumn Names frm the menu bar.
Clumn ptins If yu rightclick a clumn heading, several ptins will appear in the ppup menu. Yu can cntrl clrs, fnts, and view the clumn attributes. Yu can chse t srt the data by the values in the clumn. If yu are nt in edit mde, then yu are given the ptin f creating a new data set cntaining the srted data. Yu can als hide r hld clumns. If yu chse t hide a clumn, the data will nt be visible in the current Viewtable sessin. T unhide a clumn, select Data ► Hide/Unhide frm the menu bar t pen the Hide/Unhide windw. In this windw yu can change the visibility f all clumns. When yu chse t hld a clumn in a data with lts f clumns, it and every clumn t the left f it will always be visible , even when yu scrll t the right.
Viewing the Prperties f Data Sets with SAS Explrer
The Prperties windw fr a SAS data set cntains sme very useful infrmatin, such as the date and time the data set was created, the number f bservatins, all the variable names, and the attributes f the variables. The Prperties windw cntains infrmatin similar t the utput prduced by the CNTENTS prcedure .
pening the Prperties windw T pen the Prperties windw, start by dubleclicking the Libraries icn in the Explrer windw and then dubleclicking the library cntaining the SAS data set. SAS will display the cntents f the library in the Explrer windw. Rightclick the icn fr the data set, and select Prperties frm the ppup menu. This pens the Prperties windw with the General tab n tp. This figure shws what the Prperties windw lks like in the Micrsft Windws perating envirnment.
General tab This windw displays infrmatin abut the data set such as the date it was created and the number f rws (r bservatins) and clumns (r variables).
Clumns tab If yu click the Clumns tab, SAS displays infrmatin abut the clumns (r variables) in that data set. The variable name, type, and length are displayed alng with any frmats r infrmats assigned t the variable. The variable labels are als displayed in this windw, but t see them yu need t scrll t the right.
Yu can srt any f these clumns alphabetically by clicking the clumn heading. This windw shws the variables srted by name. Yu can find a clunm by typing its name in the bx labeled Find clumn name.
69
Dataset cmpnents
Dataset Name
Variable
bservatin
Value
86
SAS Dataset Terminlgy
SAS Dataset
Variable
bservatin
Value (cell)
= SAS table
= Clumn
= Rw
= Value
72
Rules fr Name (Dataset & Variable)
Start with a letter r an underscre
Cntain nly letters, numbers r underscres
32 characters r fewer
Nte: fr libref8 characters r fewer
73
System Reserved Variable Names:
_n_ _errr_ _all_
_char_ _character_ _numeric_
_freq_ _type_ _stat_
Nte: SAS is case sensitive nlyfr value cells.
Fr variable names SAS is insensitive t case s yu can use uppercase, lwercase, r mixed case—whichever lks best t yu. SAS desn’t care. The data set name heightweight is the same as HEIGHTWEIGHT r HeightWeight. Likewise, the variable name BirthDate is the same as BIRTHDATE and birThDaTe. Hwever, there is ne difference fr variable names. SAS remembers the case f the first ccurrence f each variable name and uses that case when printing results.
Hint: SAS is typically case sensitive. Yu will find that file names, library names, variable names and language elements are NT case sensitive fr example SAS statements can be in upper r lwercase, but that peratins n string variables (e.g. name = "Jhn") ARE case sensitive. Thus, when yu want t make string peratins case insensitive, yu must take precautins (e.g. upcase(name) = "JHN").
74
Select the valid SAS name:
1)
data5mn
2)
5mnthsdata
3)
Data#5
4)
Five mnths data
5)
fivemnthdata
6)
FiveMnthsData
In SAS there are just tw data types: numeric and character. Numeric fields are, well, numbers. They can be added and subtracted, can have any number f decimal places, and can be psitive r negative. In additin t numerals, numeric fields can cntain plus signs (+), minus signs (), decimal pints (.), r E fr scientific ntatin. Character data are everything else. They may cntain numerals, letters, r special characters (such as $ r !) and can be up t 32,767 characters lng. Hwever, if it cntains nly numbers, then it may be numeric r character.
If a variable cntains letters r special characters, it must be a character variable. Hwever, if it cntains nly numbers, then it may be numeric r character. SIN , fr example, are made up f numerals, but it just desn’t make sense t add, subtract, multiply, r divide SIN r fr ID clumn that has a values like 001,002,…
Values:
76
SAS Variable Values: There are 2 types f Variables
Character
Default length
8bytes
Length
1–32,767(Bytes)
(Casesensitive)
Numeric
8bytes
38(Bytes)
* The length f a numeric variable lies between 3 and 8 bytes. It means SAS can stre a numeric value frm 1 t 16 digits.
any character needs 1 byte t stre as an example t stre Hamid we needs at least 5 bytes.
77
Pssible Strage Lengths fr Integer Values (Windws and UNIX)
Length (bytes)
Largest Integer Represented Exactly
3
8,192
4
2,097,152
5
536,870,912
6
137,438,953,472
7
8
35,184,372,088,832
9,007,199,254,740,992
78
SAS DateValue:
SAS stres date values as numeric values
01Jan1959
01Jan1960 01Jan1961
stre
365
0 366
display
01/01/1959 01/01/1960 01/01/1961
As an exampleSAS stres 2 Jan1960 with 1 , 25 Jan1960 with 24
79
Missing Data Valuesare encded using Perid(dt):
A Character missing value is displayed as ablank
A numeric missing value is displayed as a perid(.)
Missing Data
81
SAS datasets have a
DescriptrPrtin
DataPrtin
82
Descriptr Prtin (1) :GeneralInfrmatin
Dataset name
Dataset label
Date/Time created
Strageinfrmatin
Number fbservatins
83
Descriptr Prtin (2):Infrmatin fr eachvariable
Name
Type
Length
Psitin
Frmat
Infrmat
Label
02Nv23 110
Brwsing the Descriptr Prtin
There is an easy way t get a descriptin f a SAS data set; yu simply run the CNTENTS prcedure. PRC CNTENTS is a simple prcedure. Yu just type the keywrds PRC CNTENTS and specify the data set yu want with the DATA= ptin:
PRC CNTENTS DATA = dataset;
prc cntents data=Sashelp.Cars;
run;
SAS DATA SET CMPNENTS
88
1. Every SAS statement ends with a .
2.
Character variable value can be up t characters lng and use byte(s) f strage per character.
3.
A SAS variable name has t
characters and begins with a r
.89
1. Every SAS statement ends with a semicln.
2. Character variable value can be up t 32,767
characters lng and use character.
3. A SAS variable name has
1 byte(s) f strage per
1 t 32
characters
and begins with a letter r an underscre.
90
1. By default, numeric variable are stred in bytes f strage.
2.
The internally stred SAS date value fr January 1,1960, is .
3.
A missing character value is displayed as a .
4.
A missing numeric value is displayed as a .
91
1. By default, numeric variable are stred in 8 bytes f strage.
2.
The internally stred SAS date value fr January 1,1960, is 0 .
3.
A missing character value is displayed as a blank.
4.
A missing numeric value is displayed as a perid.
92
1. What are the tw kinds f steps?
2.
What are the tw prtins f every SAS dataset?
3.
What are the tw types f variables?
93
1. What are the tw kinds f steps? A: DATA and PRC
2.
What are the tw prtins f every SAS dataset? A: Descriptr and Data
3.
What are the tw types f variables? A: Character and Numeric
94
If a SAS prgram prduces utput, then the prgram ran crrectly and there is n need t check the SAS lg.
mitting a semicln never causes errrs.
95
If a SAS prgram prduces utput, then the prgram ran crrectly and there is n need t check the SAS lg.
A: False
mitting a semicln never causes errrs. A: False
Are SAS Statements case sensitive and free frmat?
Answer:
SAS Statements are free frmat
ne r mre blanks r special characters can be used t separate wrds
They can begin and end in any clumn
A single statement can span multiple lines
Several statement can be n the same line
SAS is typically case sensitive. Yu will find that file names, library names, variable names and language elements are NT case sensitive fr example SAS statements can be in upper r lwercase, but that peratins n string variables (e.g. name = "Jhn") ARE case sensitive. Thus, when yu want t make string peratins case insensitive, yu must take precautins (e.g. upcase(name) = "JHN").
Which f the variable names are allwable in SAS v9?
a. prduct1b. prduct_1
c. Prd_1 d. prd1
e. 1stname f. _1stname
g. _name_ h. firstname
i. male_femj. M/F
k. SEX_malem. _n_
Slutin
a,b,c,f,g,h,i,k,m
*Fr addig line numbers: select Prgram Editr windw then g t Tls tab > ptin >
Enhanced Editr. In General tab check Shw line numbers in its check bx.;
*==================================
Tw methds fr writing cmments:
===================================;
*yur cmment;
/*yur cmment */
*==================================
Tw basic building blcks:
===================================
SAS prgrams are cnstructed frm tw basic building blcks:
1.DATA Steps (starts with data keywrd)
2.PRC Steps (starts with prc keywrd)
DATA and PRC steps are made up f statements. A step
may have as few as ne r as many as hundreds f
statements.
We nrmally use data step fr imprting a dataset r creating a new dataset,
r getting a subset f data set, r manipulating a dataset
and we use prc step t print, summerize , r visualize data;
*nte: Sas is case sensitive nly fr values inside its data but fr keywrds and identifires( name f variables,
name f tables, ...) is nt case sensitive;
*nte: yu have t put semicln at the end f each statementl;
* fr executin: highlight the blck f cde that has t have run keywrd at the end
then select running persn icn r F3 r run tab==>submit;
*Nte: after any executin yu must check the lg even if yu get the result;
Data test1;*test1 is the name f table(=dataset) that will be saved in wrk library;
a=2;
b=3;
c=A+b;* SAS is case sensitive nly fr values inside a table nt fr thers;
run;
* i used the abve data step t craete a data nw fr print that data I will use prc print;
prc print data=test1;* test1=wrk.test1;
run;
/* I want t create a table with inf belw
id name age
1 Hamid 41
2 Haiqing 60
3 Banu 18
4 Mahhi 21
*/
data wrk.test2;/*wrk.test2 is the same as test2*/
input id name $ age;
cards;
1 Hamid 41
2 Haiqing 60
3 Banu 18
4 Mahhi 21
;
prc print data=test2;
run;
*any dataset in SAS has tw leveles fr naming like Sashelp.CARS , first we must mentin the name f libraray
then dt after that name f data set
Nte: yu can skip typing the name f library nly if it is wrk libraray i.e. EURPEANCAR=WRK.EURPEANCAR
NTE: Wrk library is the nly temprary libraray that means all yu have there will be disappear after clsing
current sessin;
/*temp.data1 ==> the name f library is temp but it is permanent library( the nly temprary library is wrk)
*/
prc print data=sashelp.class;
run;
prc print data=sashelp.cars;
run;
* Get subset f sashelp.cars that includes nly Eurpean cars;
*highlight line 78 t 84 and execute;
DATA EURPEANCAR;*We start a data step t create a dataset that its name is EURPEANCAR , EURPEANCAR is utput data;
SET Sashelp.CARS;/*Sashelp.CARS is input data that I want t get subset f it */
WHERE rigin = "Eurpe"; *I added a cnditin that is rigin = "Eurpe";
*Nte: SAS is case sensetive nly fr values f tables;
*yu shuld put run statement at the end and highlight them tgather then hit the running persn icine fr executing;
prc print data =eurpeancar;
run;
**syntax rules;
*SAS Prgram is a series f SAS statement;
*Mst Statement nt all f them begin with an identifying keywrd;
*SAS statement must end with semicln ==> s, fr calculating number f statements cunt number f semiclns;
*These statement execute in rder i.e. bservatin by bservatin ,and fr ecah bservatin line by line (statement by statement),
That means SAS takes first bservatin and runs it all the way
thrugh the DATA step (line by line) befre lping back t pick up
the secnd bservatin.;
*====================================================================================;
*SAS terminlgy ;
*====================================================================================;
*data set=SAS Table;
*Variable (var) =clumns;
*bservatin(bs)=rws(recrds);
* data values (val)=intersectinal between Rws and Clumn;
*=======================================================================================;
*NAMING CNVENTINS FR SAS TABLES and VARABILES;
*========================================================================================;
*1. START WITH A LETTER R AN UNDERSCRE;
*2. CAN CNTAIN NLY LETTERS,NUMBERS,AND UNDERSCRES;
*3. CAN BE 32 CHARACTERS R FEWER;
*=====================================================;
*NAMING CNVENTINS FR SAS LIBRARY(libref);
*======================================================;
*1. START WITH A LETTER R AN UNDERSCRE;
*2. NLY LETTERS,NUMBER,UNDERSCRE;
*3. 8 CHARACTERS R FEWER;
*=============================================================
Type f libraries
==============================================================;
*SAS LIBARY:we have tw types f library:
1.PERMANENT AND 2.TEMPRARY SAS LIBRARY
* The nly temprary library is wrk==> all f the ther libraries are permanent;
/*The WRK library is the nly temprary strage lcatin fr SAS data sets.
It is als the default library. If yu create a SAS data set withut specifying a library, SAS
will put it in the WRK library, and then delete it when yu end yur sessin.*/
*=====================================================================
TYPE F DATA VALUES
======================================================================;
*TYPE F DATA VALUES : 1.Numeric r 2.chategric:
If a variable cntains letters r special characters, it must be a character(categric)_ variable.
Hwever, if it cntains nly numbers, then it may be numeric r character.
i.e. fr numeric values yu are allwed t assign a numeric r charectr data type
Fr example yu can stre value=100 t numeric variable and charactr variable
but yu can stre value="Hamid2" nly in cahractr variable
If YU STRTE "HAMID2" IN NUMERiC VARAIBLE YU WILL GET MISSING VALUES;
* IN SAS we cnsider tw types fr numbers :
1.standard like 348 0r 102.5 that desn't have any special charectrs and
2.nnstandard numbers like 25% r 02122022 r $152 r 3,245
fr reading nnstandard numbers we must specify the frmat f them(we call it infrmat and I will talk abut that);
*NUMERIC :1. Standard numbers 345678432, 156.8 , 267.9
2. NN STANDARD NUMERIC DATA : have $, %, cma( like 2,564,790) ,dates,..
NTE:dates in SAS are NNSTANDARD numeric and if yu read them with the prper infrmat
they are stred as a number f days between that date and
date base (date base is 1st f Janurary 1960)
as an example if SAS read 10Jan1960 with prper framt it stres it with value equals t 9 ((10Jan1960) (1Jan1960))
;
*CHARACTER: values like "ABCDE","hamid rajaee","5 years" can stre nly in charectr varibles;
/*numeric value: cntains nly numbers, and smetimes a decimal pint and/r minus sign. When they are read int
a SAS data set, numeric values are stred in the flatingpint frmat native t the perating envirnment.
Nnstandard numeric values can cntain ther characters as numbers; yu must use frmatted input t enable SAS t read them.*/
/*nnstandard data is data that can be read nly with the aid f infrmats. Examples f nnstandard data include
numeric values that cntain cmmas, dllar signs, blanks, date and time values; and hexadecimal and binary values.
Nte: If yu stre charectr value r nnstandard numeric value in numeric variable withut specifying the prper frmat
SAS will stre missing valuees there
*/
data test2;
input id name $ age; *we need t specify charectr varibles using $ after them;
/*fr inserting values in SAS use datalines r cards satement */
datalines;
001 Hamid 41
002 Nick 6
003 Rasul 40
;/* if yu want t insert data maually type datalines r cards then semicln then
values, after inserting values semcln must be in the next line if yu put in the last line that bs wn't be inserted*/
run;
*this is simple list input that values are separted by space and have default length(8 bytes)
and we dn't have nnstandard numeric. If these cnditins are nt satisfied yu shuld use clumn input,
frmated input r mixed input that I will teach yu in later
Nte: in simple list input when yu insert values fr missing values yu must type dt
and when yu print them yu will see dt fr numeric missing values and blank fr charectr missing values
;
prc print data=test2;
run;
/*in the basic way f inserting VALUES(simple list input)
1.yu must type dt fr any missing values and
2.all values must be separated by at least ne space( 2 spaces r mre is the same as ne space
3.All chrectr values must have atmst 8 chrectrs( the rest f that wn't be saved in simple list input)*/
data test3;
input id name $ age;
cards;
001 Hamid .
002 . 6
003 Rasul 40
;
run;
prc print data=test3;
run;*in the result/utput missing values will be seen as a blank fr chrectrs and as a dt fr numbers
but be ntice that when yu insert them in the simple list input yu must type dt fr bth f them;
data test4;
input id $ name $ age; *yu can stre numbers in numeric r cahrectr varibles
but yu can't str charectr in numeric varibles . If yu d that yu will get missing values;
cards;
001 Hamid 40
002 Nick 6
003 Rasul 40
;
/* cards r datalines are used t specify that yu want t insert sme values in the table*/
run;
prc print data=test4;
run;
data test5;
input id name age; *yu can stre numbers in numeric r cahrectr varibles
but yu can't str charectr in numeric varibles . If yu d that yu will get missing values;
cards;
001 Hamid 40
002 Nick 6
003 Rasul 40
;
/* cards r datalines are used t specify that yu want t insert sme values in the table*/
run;
prc print data=test5;
run;
*======================================================================
Length f values
=======================================================================;
*
Character Length 1–32,767 bytes(Case sensitive) Default 8 bytes
( fr each charectr yu need 1 byte)
Numeric Length 38 bytes Default 8 bytes(16 digits);
data test5;
input id $ name $ age;
cards;
001 Hamid_Rajaee 41
002 Nick 6
003 Rasul 40
;
run;
prc print data=test5;
run;* since it is simple list input the deafult length is 8 bytes s yu can stre up t 8 charectrs fr chrectr values,
* The length f a numeric variable lies between 3 and 8
bytes. It means SAS can stre a numeric value frm 1 t
16 digits.
any character needs 1 byte t stre as an example t
stre Hamid we need at least 5 bytes and fr string Hamid_Rajaee yu need at least 12 bytes.
;
data test6;
length name $ 15;
input id $ name $ age;
cards;
001 Hamid_Rajaee 41
002 Nick 6
003 Rasul 40
;
run;
prc print data=test6;
run;
*___________________________________________________________________;
/*Hint: 1)sas prgram is a series f sas statements
2)Mst sas statement begins with an identifying key wrd like data,set,where,prc,..
all sas statements must end with semicln(;)*/
/*, hint : if running f yur prgram takes lng time g t icne !(break) in abve tlbar and hit that*/
/* SAS reads bservatin by bservatin and executes line by line fr each bservatin */
*=====================================================================;
/*cmment:*/
*======================================================================;
*Cmments are clred green
Nte:yu shuld put yur cmment between asterisk and semicln r between frward slash asterisk and asterisk frward slash;
* yur cmment ; /*These cmments cannt cntain internal semiclns r unmatched qutatin marks.*
/* r */
/* yur cmment*/ /*These cmments can cntain semiclns and unmatched qutatin marks.
Tip: When using cmments within a macr definitin r t hide text frm the SAS macr facility,
use this style cmment*/
/*r In the Micrsft Windws perating envirnment, if yu use the Enhanced Editr,
yu can cmment ut a blck f cde by highlighting the blck and then pressing CTRL and / (frward slash) tgether.
T uncmment a blck f cde, highlight the blck and press CTRL and SHIFT and / (frward slash) tgether.
*/
*==========================================================
Tw basic building blcks f SAS prgram
===========================================================;
/* the prgram cntains 2 steps:
1)data step
2)Prc step
we use prc step t craete a reprt r graph , ...*/
/*SAS statement usually begins with a keywrd and end with a semicln ==> each semicln ne statement*/
* Every time Check the lg t make sure
the prgram run withut errrs r warnings;
DATA EURPEANCAR;*we created (writing) a temprary data set that is EURPEANCAR r wrk.EURPEANCAR ;
SET Sashelp.CARS;*Sashelp.CARS is input data set(we reading permanent data set that its name is cars and it
is availbale in sashelp libraray);
WHERE rigin = 'Eurpe' ;*'Eurpe'="Eurpe";
run;
*in abve data step Sashelp.CARS is input data set and EURPEANCAR r WRK.EURPEANCAR are utput data set ;
*=======================================================
Brwsing Data Prtin and descriptr prtin
=========================================================;
/*Brwsing Data Prtin*/
Prc print data=EURPEANCAR;
run;
/*Brwsing the Descriptr Prtin*/
prc cntents data=EURPEANCAR; *be nticed that we have s at the end f cntents;
run;
*=====================================================================================;
*ceating Library;
*=====================================================================================;
/*creating libraray*/
/*SAS datasets can be temprary r permanent.
Temprary SAS datasets nly exist during the current SAS sessin.
Permanent SAS datasets are saved t a lcatin n the cmputer r server and exist after exiting SAS.
Unless therwise specified t be permanent, SAS cnsiders all datasets t be temprary
data1=wrk.data1 */
/*There are a few guidelines t keep in mind when yu create the name f yur library.
Library names(libref name):
1.are limited t eight characters.
2.must begin with a letter r underscre.
3.can cntain nly letters, numbers, r underscres. Blanks are nt allwed.*/
/*create yur library :1) by cding r 2) by using GUI( Graphical user interface):
* befre it create a flder in the server r yur cmputer;
using GUI:Yu can als create a new SAS library by pening
the New Library windw frm the Libraries sectin f the navigatin pane in SAS Studi:
icne new library in up tlbar r Explrer windw ==>Right click n Library ==> New): give the name fr example hmd,
enable at start up,
chse yur path and k **/
* I want t create a subset f sashelp.cars in my library;
data hr.ecar;
set sashelp.cars;
where rigin='Eurpe';
run;
/*by cding:g t any drive fr example.C:\Users\hmdra\Desktp\Metr Cllege_Teaching Materials\SAS\My sas library
and create a flder fr example My sas library then cpy its address and cme back t sas and write the keywrd libname
and give any name yu want as a libref fr example Hmd and then
paste just the address in single r duble qutatin */
libname h1 "C:\Users\hmdra\Desktp\Metr Cllege_Teaching Materials\SAS\My sas library";
/* highlite the cde and F3 r chse the runnig persn icne*/
/*Fr any SAS sessin, Yu need t submit a LIBNAME statement (nly nce during each SAS sessin)
The libref remains in effect fr the duratin f that sessin.
But the data that yu stred in that library exist fr ever until yu delete them,
but in any sessin yu shuld say where that library is lcated .
Nte:Yu can assign different names fr libref fr the same
lcatin and use it i.e.
The libref can change, but the member name( file name = dataset names), and directry must the same.
(A libref is just a nickname that crrespnds t the lcatin f a SAS data library. )
as an example fr the same flder I will assign anther name as well*/
libname h2 "C:\Users\hmdra\Desktp\Metr Cllege_Teaching Materials\SAS\libreary fr practice";
*==========================================================;
*LIBNAME statement
*===========================================================
A LIBNAME statement cnsists f
1.the keywrd LIBNAME.
2.the libref name that yu want t use.
(that have at mst 8 charects and starts with letter r underscre and cntain leters, underscre and numbers)
3.the pathname that represents the physical lcatin f the library and wrapped in sigle r duble qutatin marks.
4.a semicln.;
/*after every run check lg*/
data eur;
set Sashelp.cars;
where rigin= "Eurpe";
run;
*It created a temprary data set that its name is eur inside wrk libary eur=wrk.eur;
/*If yu have a data in wrk library that yu need fr future yu shuld better t save as in permanent library*/
/*t get a save as(cpy and paste) eur dataset;*/
data h1.eur2;*eur2 is the utput dataset in permanent library , eur is the input data in wrk (temprary) library;
set eur;
run;
*It created a permanent data set that its name is eur inside h1 libary;
prc print data=h1.eur;* if Yu dn't mentin which data SAS will execute fr the mst recent data;
run;
prc print;run;
data h1.Asia;*utput data is h1.asia;
set Sashelp.cars;*input data is sashelp.cars;
where rigin= "Asia";* be ntice that unlike SQL that yu are allwed t use nly single qutes t wrap the charectr values, In SAS yu can use either single r duble qutes;
run;
prc print;* in prc if yu skip mentining name f data ,that prc run fr the mst recent data that yu wrked n it;
run;
data h1.USA;
set Sashelp.cars;
where rigin= "USA";
run;
prc print Data =Asia;* yu will get an errr beacause asia is stptred in h1 nt wrk;
run;
prc print Data =h1.asia;
run;
*===========================================
Using SAS fr calculatin
*===========================================;
*find 2*3
*Methd #1:yu can use macr variable that I will teach yu latr
*Methd #2: using data step and prc step;
*highlite the next 4 lines and execute tgether;
data calculatin;
result=2*3;*whenever yu use a new name in datastep SAS will craete a new variable with that name ;
prc print ;
run;
data cal;
x=2;
y=3;
result=x*y;
run;
prc print data=cal;
run;
* Example:Create a SAS data set named distance and Cnvert 26.22 miles t kilmeters;
DATA distance;
Miles = 26.22;* By using new name yu can create new clumn(variable);
Kilmeters = 1.61 * Miles;
RUN;
* Print the results;
PRC PRINT DATA = distance;
RUN;
*=================================================
d ... end
*====================================================;
* Example:Create a SAS data set named distance_2 and cnvert 1 t 20 miles t kilmeters;
data distance_2;
d miles = 1 t 20;
kilmeters = miles * 1.61;
utput;* fr saving result f any iteratin in distance_2;
end;
run;
* I will talk abut lp later in details;
*We have differnt types f lp and I will talk abut lping mre in day7 ;
prc
data=distance_2;
run;
*Missing Data Values :
A Character missing value is displayed as a blank
A numeric missing value is displayed as a perid (.);
/*
SAS Statements are free frmat:
ne r mre blanks r special characters can be used t separate wrds
They can begin and end in any clumn(i.e. yu can put spaces at the begining)
A single statement can span multiple lines
Several statement can be n the same line
but becarefull that each staement must be ended with semicln
*/
/*In any sessin yu shuld specify where that library is lcated .Yu can assign different name fr libref fr
same lcatin and use it i.e.
The libref can change, but the member name( file name), and directry must the same.
(A libref is just a nickname that crrespnds t the lcatin f a SAS data library. )
*/
*
craete a data in SAS (manually ie. by inserting values) :
step1: assigning a name fr data(table) (After data keywrd)
stpe2: assigning names fr variables(clumns) and assigning data type fr them (after input keywrd)
step3: inserting values (after cards r datalines keywrd)
;
data my_1st_data;*utput data is my_1st_data=wrk.my_1st_data that is temprary data;
input name $ age gender $ weight height;/* we use input statement t assign variable's name= clumn's name=header :
variables'name:
1)are limited t 32 characters.
2)must begin with a letter r underscre.
3)can cntain nly letters, numbers, r underscres. Blanks are nt allwed*/
*T create a character clumn, specify a $ sign righ after the sapace after
clumn name.;
*Nte: unlike SQL that we use cmma t separate clumns names in SAS we use sapace;
* when yu insert values in simple list input separater is space(at least 1 space) and Any missing data must be indicated with a perid.;
*Nte:recall that when yu print a table fr missing values yu will see perid fr numeric clumns and blank fr categrical clumns;
/* Fr inserting data yu shuld type cards r datalines then semicln and in new rws type bservatins after
the last bservatins(rws) g t new line and type semicln*/
*fr inserting values use cards r datalines;
cards;
Hamid 41 . 82 185
Nick . M . 124
Sarah 34 F 76 167cm
. 4 F 18 115
Aryan 12 M 67 156
Rsa 34 F 57 163
;
*yu must put semicln after the last bs in "new line" if yu put semicln at the end f bs thet ne wn't be inserted;
run;
*S imprtant: after any executin in SAS yu must check the lg t make sure that result is reliable r nt;
prc print;run;*in any prcedure if yu skip calrifying name f data , that prc excute fr the last data that is executed;
**in result utput characters are n left side, numeric are n the right side;
*Nte: fr numeric variable if yu insert charectr yu will get missing values;
* I stred that privuse data set in wrk library, Since it is temprary libraray after clsing the SAS prgram ,
this data is ginig t be disapear. If yu want t save it permanently yu have t create that data in permanent
library r getting save as like ;
Data Hamid.myData;*Hamid.myData is utput data that I want t save in in Hamid libraray;
*nte: yu can save it with the same name like Hamid.my_1st_data;
set my_1st_data;*my_1st_data is input data that exits in wrk libraray and I want t get a cpy f it;
Run;* I created new data set in hamid library and I named it mydata and I save as all data that I have in my_1st_data;
data test_1;
input id name $ family $ height ;* several sapces is the same as ne space;
/*cards=datalines*/
cards;
001 Hamid Rajaee 184.7
002 Mudasir khan 164.6
003 Nick rajaee 154.2
;
run;
prc print data=test_1; run;
prc print data=test_1 nbs; run;
* yu can save numbers as a charectr as well;
data test_2;
input id $ name $ family $ height ;* several sapces is the same as ne space;
cards;
001 Hamid Rajaee 184.7
002 Mudasir khan 164.6
003 Nick rajaee 154.2
;
run;
prc print data=test_2; run;
data h1.test2;
length name $ 15;
input id $ name $ age;
cards;
001 Melaku_Tessema 45
002 Nazreit_zeleke 40
003 Bilen_Tesfaye 11
;
run;
prc print;run;
data mytable;
input Id Name $ Age Tell $ Height;
datalines;
1 Hamid . 41 6479964597 185
2 Fu 23 4169873245 176
3 Ajana 21 6479988976 .
4 shiva 20 6476573245 177
5 kamal 36 4169870876 177
;
run;
PRC PRINT data=mytable;RUN;
/*Brws Data descriptr*/
prc cntents data=mytable;run;
* fr inserting any nnstandard numbers in yur dataset( table) yu must use infrmat;
*************************************************************
inframt Vs. frmat
************************************************************;
* fr reading and writing nnstandard numeric values yu can use inframt( fr writing/inserting values)
and frmat( fr reading/printing values);
data mytest;
input id name $ family $ age db;* several sapces is the same as ne space;
infrmat db ddmmyy8.;*infrmat fr reading perpuse (inserting in table)
Nte:right after each frmat_name put dt;
cards;
001 Hamid Rajaee 41 14.05.85
002 Mudasir khan 32 9.01.60
003 Nick rajaee 6 20.12.10
;
run;
*nte: sme availble frmat :
14.05.85 r 14/05/85 ==>ddmmyy8. r ddmmyy.
17/03/2013 ==>ddmmyy10.
03/17/2013 ==>mmddyy10.
17MAR13 ==>Date.
17MAR2013 ==>Date9.
yu can find mre by typing date frmat in help windw( use help tab)
;
/*SAS stres date values as numeric values and shwes us differnce dayes frm 1Jan1960(base date in SAS*/
/*Fr reading date t sas(Infrmat) we shuld specify frmat f date*/
/*Nte:mmddyy6. is ne type frmat fr date that mentin 1st 2 digit is mnth , 2nd 2 digit is day and
3rd 2 digit is year*/
* after checking a lg yu will find that this data is created successfully;
* but when yu print the data yu will see sme numbers fr db since SAS returns the number f days differences frm 1st f Jan1960;
prc print data=mytest;run;
* we use infrmat fr reading and we use frmat fr writing;
* t see the result fr db in undrstanding frm use frmat statement;
prc print data=mytest;
frmat db ddmmyy8.;
run;
prc print data=mytest;
frmat db ddmmyy.;
run;
prc print data=mytest;
frmat db date9.;
run;
prc print data=mytest;
frmat db weekdate.;
run;
* yu can use any ther date frmat;
*yu can find all avaible ptins fr date frmat by ging help then type date and then select Abut SAS Date, Time, and Datetime Values;
prc print data=mytest;
frmat db ddmmyy10.;
run;
prc print data=mytest;
frmat db date9.;
run;
prc print data=mytest;
frmat db weekdate32.;
run;
data mytest;
input id name $ family $ age db;* several sapces is the same as ne space;
infrmat db ddmmyy8.;/*infrmat fr reading perpuse and frmat fr writing perpuse fr dates, yu can assign frmat in data step r prc step*/
frmat db date9.;
/*if yu define frmat in data step it will saved with it but yu can verride whenever yu want */
cards;
001 Hamid Rajaee 41 14.05.85
002 Mudasir khan 32 9.01.60
003 Nick rajaee 6 20.12.10
;
run;
prc print data=mytest;
run;
prc print data=mytest;
frmat db ddmmyy10.;
run;
prc print data=mytest;
frmat db mmddyy10.;
run;
评论
发表评论