lezione1 sas
DESCRIPTION
Introduzione corso SASTRANSCRIPT
Lezione 1: Overview di SAS, i data sets, la libname, sintassi SAS
• SAS è un pacchetto statistico molto potente e strutturato composto da più ‘pacchetti’
COS’E’ SAS?
• Quelli trattati nel corso:
– SAS\BASE Procedure e passi base
– SAS\STAT Per le elaborazioni Statistiche
– SAS\GRAPH Per la produzione di Grafici
LA STRUTTURA
COSA PUOI FARE CON SAS?
• Come la maggior parte dei sistemi SAS è formato dal programma e dall’interfaccia.
• L’interfaccia è costituita da tre principali finestre:
– PROGRAM EDITOR– OUTPUT– LOG
In aggiunta alle tre finestre l’interfaccia è composta da diversi menù a tendina che permettono di accedere alle varie funzionalità del programma.
L’ INTERFACCIA
Finestra OUTPUT
Finestra EDITOR
Finestra LOG
Librerie dei Dati
• Nell’EDITOR vengono definite le istruzioni che comporranno il programma.
Istruzioni che devono seguire l’insieme delle regole del linguaggio SAS, ovvero la sintassi del linguaggio.
Le istruzioni vengono eseguite attraverso il comando run (richiamabile attraverso i tasti F3 e F8 della tastiera).
Le istruzioni vengono eseguite nell’ordine in cui sono state definite nell’editor.Una volte eseguite le istruzioni è possibile consultare la finestra OUTPUT per visualizzare gli eventuali risultati delle procedure, e la finestra LOG per verificare che il codice lanciato non abbia causato errori.
FINESTRE PRINCIPALI - EDITOR
Esegue il programma (F3 o F8)
Nuovo editor Navigazione nelle librerie di dati
Nell’OUTPUT vengono visualizzati i risultati visivi delle procedure e delle istruzioni eseguite dal programma.
Ad esempio il contenuto di un dateset o il risultato di una procedura.
Nell’esempio viene stampato nell’output parte del contenuto presente nel dataset CARS della libreria di dafault SASHELP.
FINESTRE PRINCIPALI - OUTPUT
Nella finestra LOG vengono visualizzate informazioni sull’elaborazione, ossia segnalazioni di errore nella scrittura della sintassi, il nome degli archivi di dati che si stanno utilizzando o il numero di osservazioni che si processano.
In caso di errori durante l’esecuzione del programma nel log compariranno messaggi di errore o segnalazioni che segnalano anomalie: ogni volta che si fa girare un programma è consigliabile controllare nella finestra di LOG la comparsa di eventuali messaggi:
I più importanti sono:– ERROR– WARNING
FINESTRE PRINCIPALI - LOG
Esempio di errore: si vuole stampare una variabile non presente nel dataset.
NB. Compare in rosso la scritta ERROR nella finestra LOG
UN PROGRAMMA SAS
I passi di data servono per l’acquisizione di dati da un archivio o per la creazione di tabelle di dati (DATASET).
IL DATA STEP
• sono di diverso tipo e possono servire per:
– Eseguire l’analisi dei dati.– Acquisire dati da formati diversi da quello SAS
(dataset).– Stampare/visualizzare i dati o i risultati di altre
procedure.
LE PROCEDURE
13
Copyright © 2012, SAS Institute Inc. All rights reserved.
SAS LibrariesSAS data sets are stored in SAS libraries. A SAS library is a collection of SAS files that are referenced and stored as a unit.
Each file is a member of the library.
14
Copyright © 2012, SAS Institute Inc. All rights reserved.
SAS Libraries
14
You can think of a SAS library as a drawer in a filing cabinet and a SAS data set as one of the files in the drawer.
data set
libraries
15
Copyright © 2012, SAS Institute Inc. All rights reserved.
How SAS Libraries Are DefinedWhen a SAS session starts, SAS automatically creates one temporary and at least one permanent SAS library that you can access. These libraries are open and ready to be used.
15
temporary library
permanent library
work
sashelp
16
Copyright © 2012, SAS Institute Inc. All rights reserved.
Assigning a LibrefRegardless of the operating system that you use, you refer to a SAS library by a logical name called a library reference name, or libref.
A libref is a shortcut to the library.
16
librefwork
sashelp
17
Copyright © 2012, SAS Institute Inc. All rights reserved.
Temporary LibraryWork is a temporary library where you can store and access SAS data sets for the duration of the SAS session. It is the default library.
SAS deletes the work library and its contents when the session terminates.
work
18
Copyright © 2012, SAS Institute Inc. All rights reserved.
Permanent LibrariesSashelp is a permanent library that contains sample SAS data sets you can access during your SAS session.
sashelp
19
Copyright © 2012, SAS Institute Inc. All rights reserved.
Permanent LibrariesSasuser is a permanent library that you can use to store and access SAS data sets in any SAS session.
SAS data sets in permanent libraries are saved after your SAS session terminates.
sasuser
20
Copyright © 2012, SAS Institute Inc. All rights reserved.
Accessing SAS Data SetsAll SAS data sets have a two-level name that consists of the libref and the data set name, separated by a period.
When a data set is in the temporary work library, you can use a one-level name (for example, newsalesemps).
work.newsalesemps
sashelp.class
data set namelibref
libref.data-set-namelibref.data-set-name
data set namelibref
21
Copyright © 2012, SAS Institute Inc. All rights reserved.
User-Defined LibrariesUsers can create their own SAS libraries. A user-defined library is permanent. Data sets are stored until the user
deletes them. is implemented within the operating environment’s file
system. is not automatically available in a SAS session.
21
22
Copyright © 2012, SAS Institute Inc. All rights reserved.
The user must assign a libref to the user-defined library to make it available in a SAS session.
User-Defined Libraries
Operating Environment
A SAS library is… Example
Microsoft Windows A folder s:\workshop
UNIX A directory ~/workshop
z/OS (OS/390) A sequential file userid.workshop.sasdata
22
23
Copyright © 2012, SAS Institute Inc. All rights reserved.
Accessing a Permanent Library
Associate the libref orion with the Windows folder so that it is available to your SAS session.
librefData
Step 2 Use a SAS LIBNAME statement to associate the libref with the physical location of the library.
24
Copyright © 2012, SAS Institute Inc. All rights reserved.
LIBNAME StatementThe SAS LIBNAME statement is a global SAS statement.
It is not required to be in a DATA step or PROC step. It does not require a RUN statement. It executes immediately. It remains in effect until changed or canceled, or until the
session ends.
Use the location of your course data in yourLIBNAME statement.
libname Data"s:\workshop";
LIBNAME libref "SAS-library" <options>;LIBNAME libref "SAS-library" <options>;
25
Copyright © 2012, SAS Institute Inc. All rights reserved.
Viewing the LogPartial SAS Log47 libname orion "s:\workshop";NOTE: Libref ORION was successfully assigned as follows: Engine: V9 Physical Name: s:\workshop
26
Copyright © 2012, SAS Institute Inc. All rights reserved.
3.04 Multiple Choice PollWhich of the following correctly assigns the libref myfiles to a SAS library in the c:\mysasfiles folder?
a. libname orion myfiles "c:\mysasfiles";
b. libname myfiles "c:\mysasfiles";
c. libref orion myfiles "c:\mysasfiles";
d. libref myfiles "c:\mysasfiles";
27
Copyright © 2012, SAS Institute Inc. All rights reserved.
3.04 Multiple Choice Poll – Correct AnswerWhich of the following correctly assigns the libref myfiles to a SAS library in the c:\mysasfiles folder?
a. libname orion myfiles "c:\mysasfiles";
b. libname myfiles "c:\mysasfiles";
c. libref orion myfiles "c:\mysasfiles";
d. libref myfiles "c:\mysasfiles";
data esempio2;
set esempio;
run;
Libreria permanente:data dati.esempio;
set esempio;
run;
Libreria temporanea:data work.esempio;
set esempio;
run;
Il nome della libreria temporanea (work) si può omettere
I DATASET
What Is a SAS Data Set?
A SAS data set is a specially structured data file that SAS creates and that only SAS can read. A SAS data set is a table that contains observations and variables.
observations
variables
I DATASET
SAS Data Set Terminology
SAS Terminology Database Terminology
SAS Data Set Table
Observation Row
Variable Column
I DATASETPer creare un nuovo dataset basandosi su dati esterni si utilizzano delle procedure
di importazione di dati che vedremo in seguito.Per creare un nuovo dataset basandosi su uno già esistente si usa il comando
SET.
Usando il comando set si ottiene un nuovo dataset con le stesse variabili e le stesse osservazioni del dataset base. Nel nuovo dataset si potranno poi creare nuove variabili e nuove osservazioni.
data a;set dati.esempio;nuovaVar=altezza*2;
run;
Con questo codice si creerà un nuovo dataset (a) con le stesse variabili e osservazioni del dataset esempio della libreria dati.
Viene inoltre creata nel nuovo dataset una nuova variabile (nuovaVar) che avrà come valore il valore della variabile altezza (presente nel dataset dati.esempio) moltiplicato per 2. Questa variabile non verrà creata nel dataset di partenza (dati.esempio).
DATASET PERMANENTI E TEMPORANEI
• I Dataset sono suddivisi in due categorie:– TEMPORANEE– PERMANENTI
In default i dataset creati da SAS vengono salvati nella libreria temporanea WORK.
I dataset creati in librerie temporanee vengono cancellati alla fine della sessione SAS, quindi verranno persi quando si arresta SAS.
Per ovviare a questo problema è possibile creare delle librerie permanenti, associate a un nome logico, in cui è possibile salvare i propri dati al fine di averli disponibili all’avvio di una nuova sessione di SAS.
Per definire una libreria permanente è necessario usare l’istruzione libname, che permette di associare al nome di una libreria il percorso di una cartella dove verranno salvati i dati SAS.
L’ISTRUZIONE SETCon l’istruzione SET è possibile anche aggiungere a un dataset le
osservazioni (record) derivanti da un altro.
Ad esempio:
data a;
set dati.esempio1 dati.esempio2;
run;
Per poter usare in modo efficace il comando SET i nomi delle variabili dei due dataset che si vogliono ‘appendere’ devono essere uguali.
L’ISTRUZIONE SETdata a;
set dati.esempio1;
run;
data b;
set dati.esempio2;
run;
data c;
set a b;
run;
Il dataset A ha 2 osservazioni e 3 variabili. Il dataset B ha 2 osservazioni e 3 variabili.
Il dataset C, ottenuto con il comando set di A e B ha 4 osservazioni e 3 variabili. Per le variabili presenti in uno solo dei dataset vengono creati valori mancanti per le osservazioni provenienti dal dataset in cui la variabile stessa non era presente.
LA VISUALIZZAZIONE DEI DATASET
La visualizzazione dei dataset avviene attraverso la navigazione nelle librerie di dati.
Aprendo il dateset si vedranno tutti i dati e tutte le variabili presenti in esso.
Modalità divisualizzaz-ione dei dati
Modalità dimodifica dei dati
Nome della libreria
Dataset
LA VISUALIZZAZIONE DEI DATASET
Una volta visualizzato il dataset, è possibile visualizzare tutte le informazioni riguardante esso:
• Il numero di osservazioni;• Il numero di variabili;• Ad ogni osservazione è assegnato un numero
progressivo, che permette di identificarla in maniera univoca all’interno del dataset;
• Per ogni variabile è possibile visualizzare:– il tipo (caratteriale o numerico);– il formato applicato, che va a modificare la visualizzazione
del contenuto per quella variabile;– la label, ovvero la stringa che viene visualizzata come
intestazione della variabile;
SINTASSI
SINTASSI• Alcune regole generali riguardo la sintassi SAS:
– Ogni istruzione o comando finisce sempre con il punto e virgola (;).
– Il linguaggio SAS non distingue lettere maiuscole e minuscole nei comandi (Non è CASE SENSITIVE)
– Diverse istruzioni possono essere scritte sulla stessa riga, ma devono essere sempre separate dal <;>.
– Si possono inserire commenti nel codice del programma, il testo del commento deve essere compreso fra </*> e <*/>.
– I nomi delle variabili e dei dataset possono contenere lettere, numeri o l’underscore (_), ma il primo carattere può essere solo una lettera o l’underscore.
SYNTAX ERRORSA syntax error is an error in the spelling or grammar of a SAS statement. SAS finds syntax errors as it compiles each SAS statement, before execution begins.
• Examples of syntax errors: –misspelled keywords–unmatched quotation marks–missing semicolons–invalid options40
Quiz
•This program includes three syntax errors. One is an invalid option. What are the other two syntax errors?
41p102d04
daat work.newsalesemps; length First_Name $ 12 Last_Name $ 18 Job_Title $ 25; infile "&path\newemps.csv" dlm=','; input First_Name $ Last_Name $ Job_Title $ Salary;run;
proc print data=work.newsalesempsrun;
Quiz – Correct Answer
• This program includes three syntax errors. One is an invalid option. What are the other two syntax errors?
42
daat work.newsalesemps; length First_Name $ 12 Last_Name $ 18 Job_Title $ 25; infile "&path\newemps.csv" dlm=','; input First_Name $ Last_Name $ Job_Title $ Salary;run;
proc print data=work.newsalesempsrun;
p102d04
missing semicolon
misspelled keyword
Syntax Errors• The Enhanced Editor in SAS and the Program Editor
in SAS Enterprise Guide use the color red to indicate a potential error in your SAS code.
43
Syntax Errors•When SAS encounters a syntax error, it writes a warning or error message to the log.
•You should always check the log to make sure that theprogram ran successfully, even if output is generated.
44
ERROR 22-322: Syntax error, expecting one of the following: a name, a quoted string, (, /, ;, _DATA_, _LAST_, _NULL_.
WARNING: Data set WORK.TEST was not replaced because this step was stopped.
Quiz
•What is the syntax error in this program?
p102d05
Quiz – Correct Answer
•What is the syntax error in this program?
•The program contains unbalanced quotation marks in the DLM= option in the INFILE statement.
p102d05
L’ACQUISIZIONE DI DATI
SAS è in grado di lavorare su grandi quantità di dati, a patto che questi siano in un formato comprensibile per SAS (dalla versione 7 di SAS e per le successive formato .sas7bdat)
Quindi, al fine di poter lavorare sui dati è necessario trasformare i dati di origine in formato ASCII in tipi di file ‘utili’ a SAS.
I file ASCII per acquisire i dati possono essere suddivisi in due gruppi
• Dati in formato libero
• Dati in formato colonna
L’ACQUISIZIONE DI DATI
Per l’acquisizione di dati da file ASCII i comandi principali sono INFILE e INPUT.
Il comando INFILE permette di specificare il nome e il percorso del file contenente i dati da acquisire.
Il comando INPUT permette di definire la struttura del file, ovvero il nome e il numero di variabili e il loro formato (caratteriale o numerico).
Il modo in cui vengono definite le variabili all’interno del comando varia a seconda del file che bisognerà importare, ovvero in formato libero o in formato colonna
L’ACQUISIZIONE DI DATI
Per acquisire un file di tipo ASCII il passo di data è composto da 4 comandi principali:
– DATA: inizia il datastep. Definisce il nome del dataset e l’eventuale libreria in cui sarà salvato.
– INFILE: specifica il nome del file da acquisire.
– INPUT: descrive la struttura del file e quindi il nome e il tipo di varibili. Per le variabili caratteriali il nome
è seguito dal simbolo <$>.
– RUN: conclusione del passo di data.
QUIZ
52
Copyright © 2012, SAS Institute Inc. All rights reserved.
1. How many step boundaries does this program contain?
a. four
b. five
c. six
d. seven
data work.staff; length First_Name $ 12 Last_Name $ 18 Job_Title $ 25; infile "&path\newemployees.csv" dlm=','; input First_Name $ Last_Name$ Job_Title $ Salary;run;
proc print data=work.staff;run;
proc means data=work.staff; var Salary;run;
53
Copyright © 2012, SAS Institute Inc. All rights reserved.
1. How many step boundaries does this program contain?
a. four
b. five
c. six
d. seven
data work.staff; length First_Name $ 12 Last_Name $ 18 Job_Title $ 25; infile "&path\newemployees.csv" dlm=','; input First_Name $ Last_Name$ Job_Title $ Salary;run;
proc print data=work.staff;run;
proc means data=work.staff; var Salary;run;
54
Copyright © 2012, SAS Institute Inc. All rights reserved.
2. Which of the following is a SAS syntax requirement?
a. Begin each statement in column one.
b. Put only one statement on each line.
c. Separate each step with a line space.
d. End each statement with a semicolon.
e. Put a RUN statement after every DATA or PROC step.
55
Copyright © 2012, SAS Institute Inc. All rights reserved.
2. Which of the following is a SAS syntax requirement?
a. Begin each statement in column one.
b. Put only one statement on each line.
c. Separate each step with a line space.
d. End each statement with a semicolon.
e. Put a RUN statement after every DATA or PROC step.
56
Copyright © 2012, SAS Institute Inc. All rights reserved.
3. Which of the following steps is typically used to generate reports and graphs?
a. DATA
b. PROC
c. REPORT
d. RUN
57
Copyright © 2012, SAS Institute Inc. All rights reserved.
3. Which of the following steps is typically used to generate reports and graphs?
a. DATA
b. PROC
c. REPORT
d. RUN
58
Copyright © 2012, SAS Institute Inc. All rights reserved.
4. Does this comment contain syntax errors?
4. No. The comment is correctly specified.
5. Yes. Every comment line must end with a semicolon.
6. Yes. The comment text incorrectly begins on line one.
7. Yes. The comment contains a semicolon, which causes an error message.
/*Report created for budgetpresentation; revised October 15. */proc print data=work.newloan;run;
59
Copyright © 2012, SAS Institute Inc. All rights reserved.
4. Does this comment contain syntax errors?
4. No. The comment is correctly specified. Yes. Every comment line must end with a semicolon. Yes. The comment text incorrectly begins on
line one. Yes. The comment contains a semicolon, which causes an
error message.
/*Report created for budgetpresentation; revised October 15. */proc print data=work.newloan;run;
60
Copyright © 2012, SAS Institute Inc. All rights reserved.
5. What result would you expect from submitting this step?
a. an HTML report of the work.newsalesemps data set
b. an error message in the log
c. a LISTING report of the work.newsalesemps data set
d. the creation of the temporary data set work.newsalesemps
proc print data=work.newsalesemps run;
61
Copyright © 2012, SAS Institute Inc. All rights reserved.
5. What result would you expect from submitting this step?
a. an HTML report of the work.newsalesemps data set
b. an error message in the log
c. a LISTING report of the work.newsalesemps data set
d. the creation of the temporary data set work.newsalesemps
proc print data=work.newsalesemps run;
62
Copyright © 2012, SAS Institute Inc. All rights reserved.
6. Suppose you submit a short, simple DATA step. If the active window displays the message DATA step running for a long time, what probably happened?
a. You misspelled a keyword.
b. You forgot to end the DATA step with a RUN statement.
c. You specified an invalid data set option.
d. Some data values were not appropriate for the SAS statements that you specified.
63
Copyright © 2012, SAS Institute Inc. All rights reserved.
6. Suppose you submit a short, simple DATA step. If the active window displays the message DATA step running for a long time, what probably happened?
a. You misspelled a keyword.
b. You forgot to end the DATA step with a RUN statement.
c. You specified an invalid data set option.
d. Some data values were not appropriate for the SAS statements that you specified.
64
Copyright © 2012, SAS Institute Inc. All rights reserved.
Missing Data ValuesMissing values are valid values in a SAS data set.
A value must exist for every variable in every observation.
64
Partial work.newsalesemps
First_Name Last_Name Job_Title Salary
Monica Kletschkus Sales Rep. IV .Kevin Lyon Sales Rep. I 26955Petrea Soltau 27440
A blank represents a missing character value.
A period represents a missing numeric value.